3 * @defgroup Database Database
5 * This file deals with database interface functions
6 * and query specifics/optimisations.
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License along
19 * with this program; if not, write to the Free Software Foundation, Inc.,
20 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21 * http://www.gnu.org/copyleft/gpl.html
26 namespace Wikimedia\Rdbms
;
28 use Psr\Log\LoggerAwareInterface
;
29 use Psr\Log\LoggerInterface
;
30 use Psr\Log\NullLogger
;
31 use Wikimedia\ScopedCallback
;
32 use Wikimedia\Timestamp\ConvertibleTimestamp
;
37 use InvalidArgumentException
;
38 use UnexpectedValueException
;
43 * Relational database abstraction object
48 abstract class Database
implements IDatabase
, IMaintainableDatabase
, LoggerAwareInterface
{
49 /** Number of times to re-try an operation in case of deadlock */
50 const DEADLOCK_TRIES
= 4;
51 /** Minimum time to wait before retry, in microseconds */
52 const DEADLOCK_DELAY_MIN
= 500000;
53 /** Maximum time to wait before retry */
54 const DEADLOCK_DELAY_MAX
= 1500000;
56 /** How long before it is worth doing a dummy query to test the connection */
58 const PING_QUERY
= 'SELECT 1 AS ping';
60 const TINY_WRITE_SEC
= 0.010;
61 const SLOW_WRITE_SEC
= 0.500;
62 const SMALL_WRITE_ROWS
= 100;
64 /** @var string Lock granularity is on the level of the entire database */
65 const ATTR_DB_LEVEL_LOCKING
= 'db-level-locking';
66 /** @var string The SCHEMA keyword refers to a grouping of tables in a database */
67 const ATTR_SCHEMAS_AS_TABLE_GROUPS
= 'supports-schemas';
69 /** @var int New Database instance will not be connected yet when returned */
70 const NEW_UNCONNECTED
= 0;
71 /** @var int New Database instance will already be connected when returned */
72 const NEW_CONNECTED
= 1;
74 /** @var string SQL query */
75 protected $lastQuery = '';
76 /** @var float|bool UNIX timestamp of last write query */
77 protected $lastWriteTime = false;
78 /** @var string|bool */
79 protected $phpError = false;
80 /** @var string Server that this instance is currently connected to */
82 /** @var string User that this instance is currently connected under the name of */
84 /** @var string Password used to establish the current connection */
86 /** @var array[] Map of (table => (dbname, schema, prefix) map) */
87 protected $tableAliases = [];
88 /** @var string[] Map of (index alias => index) */
89 protected $indexAliases = [];
90 /** @var bool Whether this PHP instance is for a CLI script */
92 /** @var string Agent name for query profiling */
94 /** @var array Parameters used by initConnection() to establish a connection */
95 protected $connectionParams = [];
96 /** @var BagOStuff APC cache */
98 /** @var LoggerInterface */
99 protected $connLogger;
100 /** @var LoggerInterface */
101 protected $queryLogger;
102 /** @var callable Error logging callback */
103 protected $errorLogger;
104 /** @var callable Deprecation logging callback */
105 protected $deprecationLogger;
107 /** @var resource|null Database connection */
108 protected $conn = null;
110 protected $opened = false;
112 /** @var array[] List of (callable, method name, atomic section id) */
113 protected $trxIdleCallbacks = [];
114 /** @var array[] List of (callable, method name, atomic section id) */
115 protected $trxPreCommitCallbacks = [];
116 /** @var array[] List of (callable, method name, atomic section id) */
117 protected $trxEndCallbacks = [];
118 /** @var callable[] Map of (name => callable) */
119 protected $trxRecurringCallbacks = [];
120 /** @var bool Whether to suppress triggering of transaction end callbacks */
121 protected $trxEndCallbacksSuppressed = false;
126 protected $lbInfo = [];
127 /** @var array|bool */
128 protected $schemaVars = false;
130 protected $sessionVars = [];
131 /** @var array|null */
132 protected $preparedArgs;
133 /** @var string|bool|null Stashed value of html_errors INI setting */
134 protected $htmlErrors;
136 protected $delimiter = ';';
137 /** @var DatabaseDomain */
138 protected $currentDomain;
139 /** @var integer|null Rows affected by the last query to query() or its CRUD wrappers */
140 protected $affectedRowCount;
143 * @var int Transaction status
145 protected $trxStatus = self
::STATUS_TRX_NONE
;
147 * @var Exception|null The last error that caused the status to become STATUS_TRX_ERROR
149 protected $trxStatusCause;
151 * @var array|null If wasKnownStatementRollbackError() prevented trxStatus from being set,
152 * the relevant details are stored here.
154 protected $trxStatusIgnoredCause;
156 * Either 1 if a transaction is active or 0 otherwise.
157 * The other Trx fields may not be meaningfull if this is 0.
161 protected $trxLevel = 0;
163 * Either a short hexidecimal string if a transaction is active or ""
166 * @see Database::trxLevel
168 protected $trxShortId = '';
170 * The UNIX time that the transaction started. Callers can assume that if
171 * snapshot isolation is used, then the data is *at least* up to date to that
172 * point (possibly more up-to-date since the first SELECT defines the snapshot).
175 * @see Database::trxLevel
177 private $trxTimestamp = null;
178 /** @var float Lag estimate at the time of BEGIN */
179 private $trxReplicaLag = null;
181 * Remembers the function name given for starting the most recent transaction via begin().
182 * Used to provide additional context for error reporting.
185 * @see Database::trxLevel
187 private $trxFname = null;
189 * Record if possible write queries were done in the last transaction started
192 * @see Database::trxLevel
194 private $trxDoneWrites = false;
196 * Record if the current transaction was started implicitly due to DBO_TRX being set.
199 * @see Database::trxLevel
201 private $trxAutomatic = false;
203 * Counter for atomic savepoint identifiers. Reset when a new transaction begins.
207 private $trxAtomicCounter = 0;
209 * Array of levels of atomicity within transactions
211 * @var array List of (name, unique ID, savepoint ID)
213 private $trxAtomicLevels = [];
215 * Record if the current transaction was started implicitly by Database::startAtomic
219 private $trxAutomaticAtomic = false;
221 * Track the write query callers of the current transaction
225 private $trxWriteCallers = [];
227 * @var float Seconds spent in write queries for the current transaction
229 private $trxWriteDuration = 0.0;
231 * @var int Number of write queries for the current transaction
233 private $trxWriteQueryCount = 0;
235 * @var int Number of rows affected by write queries for the current transaction
237 private $trxWriteAffectedRows = 0;
239 * @var float Like trxWriteQueryCount but excludes lock-bound, easy to replicate, queries
241 private $trxWriteAdjDuration = 0.0;
243 * @var int Number of write queries counted in trxWriteAdjDuration
245 private $trxWriteAdjQueryCount = 0;
247 * @var float RTT time estimate
249 private $rttEstimate = 0.0;
251 /** @var array Map of (name => 1) for locks obtained via lock() */
252 private $namedLocksHeld = [];
253 /** @var array Map of (table name => 1) for TEMPORARY tables */
254 protected $sessionTempTables = [];
256 /** @var IDatabase|null Lazy handle to the master DB this server replicates from */
257 private $lazyMasterHandle;
259 /** @var float UNIX timestamp */
260 protected $lastPing = 0.0;
262 /** @var int[] Prior flags member variable values */
263 private $priorFlags = [];
265 /** @var callable|null */
267 /** @var TransactionProfiler */
268 protected $trxProfiler;
271 protected $nonNativeInsertSelectBatchSize = 10000;
273 /** @var string Idiom used when a cancelable atomic section started the transaction */
274 private static $NOT_APPLICABLE = 'n/a';
275 /** @var string Prefix to the atomic section counter used to make savepoint IDs */
276 private static $SAVEPOINT_PREFIX = 'wikimedia_rdbms_atomic';
278 /** @var int Transaction is in a error state requiring a full or savepoint rollback */
279 const STATUS_TRX_ERROR
= 1;
280 /** @var int Transaction is active and in a normal state */
281 const STATUS_TRX_OK
= 2;
282 /** @var int No transaction is active */
283 const STATUS_TRX_NONE
= 3;
285 /** @var int Writes to this temporary table do not affect lastDoneWrites() */
286 const TEMP_NORMAL
= 1;
287 /** @var int Writes to this temporary table effect lastDoneWrites() */
288 const TEMP_PSEUDO_PERMANENT
= 2;
291 * @note exceptions for missing libraries/drivers should be thrown in initConnection()
292 * @param array $params Parameters passed from Database::factory()
294 protected function __construct( array $params ) {
295 foreach ( [ 'host', 'user', 'password', 'dbname', 'schema', 'tablePrefix' ] as $name ) {
296 $this->connectionParams
[$name] = $params[$name];
299 $this->cliMode
= $params['cliMode'];
300 // Agent name is added to SQL queries in a comment, so make sure it can't break out
301 $this->agent
= str_replace( '/', '-', $params['agent'] );
303 $this->flags
= $params['flags'];
304 if ( $this->flags
& self
::DBO_DEFAULT
) {
305 if ( $this->cliMode
) {
306 $this->flags
&= ~self
::DBO_TRX
;
308 $this->flags |
= self
::DBO_TRX
;
311 // Disregard deprecated DBO_IGNORE flag (T189999)
312 $this->flags
&= ~self
::DBO_IGNORE
;
314 $this->sessionVars
= $params['variables'];
316 $this->srvCache
= $params['srvCache'] ??
new HashBagOStuff();
318 $this->profiler
= is_callable( $params['profiler'] ) ?
$params['profiler'] : null;
319 $this->trxProfiler
= $params['trxProfiler'];
320 $this->connLogger
= $params['connLogger'];
321 $this->queryLogger
= $params['queryLogger'];
322 $this->errorLogger
= $params['errorLogger'];
323 $this->deprecationLogger
= $params['deprecationLogger'];
325 if ( isset( $params['nonNativeInsertSelectBatchSize'] ) ) {
326 $this->nonNativeInsertSelectBatchSize
= $params['nonNativeInsertSelectBatchSize'];
329 // Set initial dummy domain until open() sets the final DB/prefix
330 $this->currentDomain
= new DatabaseDomain(
331 $params['dbname'] != '' ?
$params['dbname'] : null,
332 $params['schema'] != '' ?
$params['schema'] : null,
333 $params['tablePrefix']
338 * Initialize the connection to the database over the wire (or to local files)
340 * @throws LogicException
341 * @throws InvalidArgumentException
342 * @throws DBConnectionError
345 final public function initConnection() {
346 if ( $this->isOpen() ) {
347 throw new LogicException( __METHOD__
. ': already connected.' );
349 // Establish the connection
350 $this->doInitConnection();
354 * Actually connect to the database over the wire (or to local files)
356 * @throws InvalidArgumentException
357 * @throws DBConnectionError
360 protected function doInitConnection() {
361 if ( strlen( $this->connectionParams
['user'] ) ) {
363 $this->connectionParams
['host'],
364 $this->connectionParams
['user'],
365 $this->connectionParams
['password'],
366 $this->connectionParams
['dbname'],
367 $this->connectionParams
['schema'],
368 $this->connectionParams
['tablePrefix']
371 throw new InvalidArgumentException( "No database user provided." );
376 * Open a new connection to the database (closing any existing one)
378 * @param string $server Database server host
379 * @param string $user Database user name
380 * @param string $password Database user password
381 * @param string $dbName Database name
382 * @param string|null $schema Database schema name
383 * @param string $tablePrefix Table prefix
385 * @throws DBConnectionError
387 abstract protected function open( $server, $user, $password, $dbName, $schema, $tablePrefix );
390 * Construct a Database subclass instance given a database type and parameters
392 * This also connects to the database immediately upon object construction
394 * @param string $dbType A possible DB type (sqlite, mysql, postgres,...)
395 * @param array $p Parameter map with keys:
396 * - host : The hostname of the DB server
397 * - user : The name of the database user the client operates under
398 * - password : The password for the database user
399 * - dbname : The name of the database to use where queries do not specify one.
400 * The database must exist or an error might be thrown. Setting this to the empty string
401 * will avoid any such errors and make the handle have no implicit database scope. This is
402 * useful for queries like SHOW STATUS, CREATE DATABASE, or DROP DATABASE. Note that a
403 * "database" in Postgres is rougly equivalent to an entire MySQL server. This the domain
404 * in which user names and such are defined, e.g. users are database-specific in Postgres.
405 * - schema : The database schema to use (if supported). A "schema" in Postgres is roughly
406 * equivalent to a "database" in MySQL. Note that MySQL and SQLite do not use schemas.
407 * - tablePrefix : Optional table prefix that is implicitly added on to all table names
408 * recognized in queries. This can be used in place of schemas for handle site farms.
409 * - flags : Optional bitfield of DBO_* constants that define connection, protocol,
410 * buffering, and transaction behavior. It is STRONGLY adviced to leave the DBO_DEFAULT
411 * flag in place UNLESS this this database simply acts as a key/value store.
412 * - driver: Optional name of a specific DB client driver. For MySQL, there is only the
413 * 'mysqli' driver; the old one 'mysql' has been removed.
414 * - variables: Optional map of session variables to set after connecting. This can be
415 * used to adjust lock timeouts or encoding modes and the like.
416 * - connLogger: Optional PSR-3 logger interface instance.
417 * - queryLogger: Optional PSR-3 logger interface instance.
418 * - profiler : Optional callback that takes a section name argument and returns
419 * a ScopedCallback instance that ends the profile section in its destructor.
420 * These will be called in query(), using a simplified version of the SQL that
421 * also includes the agent as a SQL comment.
422 * - trxProfiler: Optional TransactionProfiler instance.
423 * - errorLogger: Optional callback that takes an Exception and logs it.
424 * - deprecationLogger: Optional callback that takes a string and logs it.
425 * - cliMode: Whether to consider the execution context that of a CLI script.
426 * - agent: Optional name used to identify the end-user in query profiling/logging.
427 * - srvCache: Optional BagOStuff instance to an APC-style cache.
428 * - nonNativeInsertSelectBatchSize: Optional batch size for non-native INSERT SELECT emulation.
429 * @param int $connect One of the class constants (NEW_CONNECTED, NEW_UNCONNECTED) [optional]
430 * @return Database|null If the database driver or extension cannot be found
431 * @throws InvalidArgumentException If the database driver or extension cannot be found
434 final public static function factory( $dbType, $p = [], $connect = self
::NEW_CONNECTED
) {
435 $class = self
::getClass( $dbType, $p['driver'] ??
null );
437 if ( class_exists( $class ) && is_subclass_of( $class, IDatabase
::class ) ) {
438 // Resolve some defaults for b/c
439 $p['host'] = $p['host'] ??
false;
440 $p['user'] = $p['user'] ??
false;
441 $p['password'] = $p['password'] ??
false;
442 $p['dbname'] = $p['dbname'] ??
false;
443 $p['flags'] = $p['flags'] ??
0;
444 $p['variables'] = $p['variables'] ??
[];
445 $p['tablePrefix'] = $p['tablePrefix'] ??
'';
446 $p['schema'] = $p['schema'] ??
null;
447 $p['cliMode'] = $p['cliMode'] ??
( PHP_SAPI
=== 'cli' || PHP_SAPI
=== 'phpdbg' );
448 $p['agent'] = $p['agent'] ??
'';
449 if ( !isset( $p['connLogger'] ) ) {
450 $p['connLogger'] = new NullLogger();
452 if ( !isset( $p['queryLogger'] ) ) {
453 $p['queryLogger'] = new NullLogger();
455 $p['profiler'] = $p['profiler'] ??
null;
456 if ( !isset( $p['trxProfiler'] ) ) {
457 $p['trxProfiler'] = new TransactionProfiler();
459 if ( !isset( $p['errorLogger'] ) ) {
460 $p['errorLogger'] = function ( Exception
$e ) {
461 trigger_error( get_class( $e ) . ': ' . $e->getMessage(), E_USER_WARNING
);
464 if ( !isset( $p['deprecationLogger'] ) ) {
465 $p['deprecationLogger'] = function ( $msg ) {
466 trigger_error( $msg, E_USER_DEPRECATED
);
470 /** @var Database $conn */
471 $conn = new $class( $p );
472 if ( $connect == self
::NEW_CONNECTED
) {
473 $conn->initConnection();
483 * @param string $dbType A possible DB type (sqlite, mysql, postgres,...)
484 * @param string|null $driver Optional name of a specific DB client driver
485 * @return array Map of (Database::ATTR_* constant => value) for all such constants
486 * @throws InvalidArgumentException
489 final public static function attributesFromType( $dbType, $driver = null ) {
491 self
::ATTR_DB_LEVEL_LOCKING
=> false,
492 self
::ATTR_SCHEMAS_AS_TABLE_GROUPS
=> false
495 $class = self
::getClass( $dbType, $driver );
497 return call_user_func( [ $class, 'getAttributes' ] ) +
$defaults;
501 * @param string $dbType A possible DB type (sqlite, mysql, postgres,...)
502 * @param string|null $driver Optional name of a specific DB client driver
503 * @return string Database subclass name to use
504 * @throws InvalidArgumentException
506 private static function getClass( $dbType, $driver = null ) {
507 // For database types with built-in support, the below maps type to IDatabase
508 // implementations. For types with multipe driver implementations (PHP extensions),
509 // an array can be used, keyed by extension name. In case of an array, the
510 // optional 'driver' parameter can be used to force a specific driver. Otherwise,
511 // we auto-detect the first available driver. For types without built-in support,
512 // an class named "Database<Type>" us used, eg. DatabaseFoo for type 'foo'.
513 static $builtinTypes = [
514 'mssql' => DatabaseMssql
::class,
515 'mysql' => [ 'mysqli' => DatabaseMysqli
::class ],
516 'sqlite' => DatabaseSqlite
::class,
517 'postgres' => DatabasePostgres
::class,
520 $dbType = strtolower( $dbType );
523 if ( isset( $builtinTypes[$dbType] ) ) {
524 $possibleDrivers = $builtinTypes[$dbType];
525 if ( is_string( $possibleDrivers ) ) {
526 $class = $possibleDrivers;
528 if ( (string)$driver !== '' ) {
529 if ( !isset( $possibleDrivers[$driver] ) ) {
530 throw new InvalidArgumentException( __METHOD__
.
531 " type '$dbType' does not support driver '{$driver}'" );
533 $class = $possibleDrivers[$driver];
536 foreach ( $possibleDrivers as $posDriver => $possibleClass ) {
537 if ( extension_loaded( $posDriver ) ) {
538 $class = $possibleClass;
545 $class = 'Database' . ucfirst( $dbType );
548 if ( $class === false ) {
549 throw new InvalidArgumentException( __METHOD__
.
550 " no viable database extension found for type '$dbType'" );
557 * @return array Map of (Database::ATTR_* constant => value
560 protected static function getAttributes() {
565 * Set the PSR-3 logger interface to use for query logging. (The logger
566 * interfaces for connection logging and error logging can be set with the
569 * @param LoggerInterface $logger
571 public function setLogger( LoggerInterface
$logger ) {
572 $this->queryLogger
= $logger;
575 public function getServerInfo() {
576 return $this->getServerVersion();
579 public function bufferResults( $buffer = null ) {
580 $res = !$this->getFlag( self
::DBO_NOBUFFER
);
581 if ( $buffer !== null ) {
583 ?
$this->clearFlag( self
::DBO_NOBUFFER
)
584 : $this->setFlag( self
::DBO_NOBUFFER
);
590 public function trxLevel() {
591 return $this->trxLevel
;
594 public function trxTimestamp() {
595 return $this->trxLevel ?
$this->trxTimestamp
: null;
599 * @return int One of the STATUS_TRX_* class constants
602 public function trxStatus() {
603 return $this->trxStatus
;
606 public function tablePrefix( $prefix = null ) {
607 $old = $this->currentDomain
->getTablePrefix();
608 if ( $prefix !== null ) {
609 $this->currentDomain
= new DatabaseDomain(
610 $this->currentDomain
->getDatabase(),
611 $this->currentDomain
->getSchema(),
619 public function dbSchema( $schema = null ) {
620 if ( strlen( $schema ) && $this->getDBname() === null ) {
621 throw new DBUnexpectedError( $this, "Cannot set schema to '$schema'; no database set." );
624 $old = $this->currentDomain
->getSchema();
625 if ( $schema !== null ) {
626 $this->currentDomain
= new DatabaseDomain(
627 $this->currentDomain
->getDatabase(),
628 // DatabaseDomain uses null for unspecified schemas
629 strlen( $schema ) ?
$schema : null,
630 $this->currentDomain
->getTablePrefix()
638 * @return string Schema to use to qualify relations in queries
640 protected function relationSchemaQualifier() {
641 return $this->dbSchema();
644 public function getLBInfo( $name = null ) {
645 if ( is_null( $name ) ) {
646 return $this->lbInfo
;
648 if ( array_key_exists( $name, $this->lbInfo
) ) {
649 return $this->lbInfo
[$name];
656 public function setLBInfo( $name, $value = null ) {
657 if ( is_null( $value ) ) {
658 $this->lbInfo
= $name;
660 $this->lbInfo
[$name] = $value;
664 public function setLazyMasterHandle( IDatabase
$conn ) {
665 $this->lazyMasterHandle
= $conn;
669 * @return IDatabase|null
670 * @see setLazyMasterHandle()
673 protected function getLazyMasterHandle() {
674 return $this->lazyMasterHandle
;
677 public function implicitGroupby() {
681 public function implicitOrderby() {
685 public function lastQuery() {
686 return $this->lastQuery
;
689 public function doneWrites() {
690 return (bool)$this->lastWriteTime
;
693 public function lastDoneWrites() {
694 return $this->lastWriteTime ?
: false;
697 public function writesPending() {
698 return $this->trxLevel
&& $this->trxDoneWrites
;
701 public function writesOrCallbacksPending() {
702 return $this->trxLevel
&& (
703 $this->trxDoneWrites ||
704 $this->trxIdleCallbacks ||
705 $this->trxPreCommitCallbacks ||
706 $this->trxEndCallbacks
710 public function preCommitCallbacksPending() {
711 return $this->trxLevel
&& $this->trxPreCommitCallbacks
;
715 * @return string|null
717 final protected function getTransactionRoundId() {
718 // If transaction round participation is enabled, see if one is active
719 if ( $this->getFlag( self
::DBO_TRX
) ) {
720 $id = $this->getLBInfo( 'trxRoundId' );
722 return is_string( $id ) ?
$id : null;
728 public function pendingWriteQueryDuration( $type = self
::ESTIMATE_TOTAL
) {
729 if ( !$this->trxLevel
) {
731 } elseif ( !$this->trxDoneWrites
) {
736 case self
::ESTIMATE_DB_APPLY
:
737 return $this->pingAndCalculateLastTrxApplyTime();
738 default: // everything
739 return $this->trxWriteDuration
;
744 * @return float Time to apply writes to replicas based on trxWrite* fields
746 private function pingAndCalculateLastTrxApplyTime() {
749 $rttAdjTotal = $this->trxWriteAdjQueryCount
* $rtt;
750 $applyTime = max( $this->trxWriteAdjDuration
- $rttAdjTotal, 0 );
751 // For omitted queries, make them count as something at least
752 $omitted = $this->trxWriteQueryCount
- $this->trxWriteAdjQueryCount
;
753 $applyTime +
= self
::TINY_WRITE_SEC
* $omitted;
758 public function pendingWriteCallers() {
759 return $this->trxLevel ?
$this->trxWriteCallers
: [];
762 public function pendingWriteRowsAffected() {
763 return $this->trxWriteAffectedRows
;
767 * List the methods that have write queries or callbacks for the current transaction
769 * This method should not be used outside of Database/LoadBalancer
774 public function pendingWriteAndCallbackCallers() {
775 $fnames = $this->pendingWriteCallers();
777 $this->trxIdleCallbacks
,
778 $this->trxPreCommitCallbacks
,
779 $this->trxEndCallbacks
781 foreach ( $callbacks as $callback ) {
782 $fnames[] = $callback[1];
792 private function flatAtomicSectionList() {
793 return array_reduce( $this->trxAtomicLevels
, function ( $accum, $v ) {
794 return $accum === null ?
$v[0] : "$accum, " . $v[0];
798 public function isOpen() {
799 return $this->opened
;
802 public function setFlag( $flag, $remember = self
::REMEMBER_NOTHING
) {
803 if ( ( $flag & self
::DBO_IGNORE
) ) {
804 throw new UnexpectedValueException( "Modifying DBO_IGNORE is not allowed." );
807 if ( $remember === self
::REMEMBER_PRIOR
) {
808 array_push( $this->priorFlags
, $this->flags
);
810 $this->flags |
= $flag;
813 public function clearFlag( $flag, $remember = self
::REMEMBER_NOTHING
) {
814 if ( ( $flag & self
::DBO_IGNORE
) ) {
815 throw new UnexpectedValueException( "Modifying DBO_IGNORE is not allowed." );
818 if ( $remember === self
::REMEMBER_PRIOR
) {
819 array_push( $this->priorFlags
, $this->flags
);
821 $this->flags
&= ~
$flag;
824 public function restoreFlags( $state = self
::RESTORE_PRIOR
) {
825 if ( !$this->priorFlags
) {
829 if ( $state === self
::RESTORE_INITIAL
) {
830 $this->flags
= reset( $this->priorFlags
);
831 $this->priorFlags
= [];
833 $this->flags
= array_pop( $this->priorFlags
);
837 public function getFlag( $flag ) {
838 return (bool)( $this->flags
& $flag );
842 * @param string $name Class field name
844 * @deprecated Since 1.28
846 public function getProperty( $name ) {
850 public function getDomainID() {
851 return $this->currentDomain
->getId();
854 final public function getWikiID() {
855 return $this->getDomainID();
859 * Get information about an index into an object
860 * @param string $table Table name
861 * @param string $index Index name
862 * @param string $fname Calling function name
863 * @return mixed Database-specific index description class or false if the index does not exist
865 abstract function indexInfo( $table, $index, $fname = __METHOD__
);
868 * Wrapper for addslashes()
870 * @param string $s String to be slashed.
871 * @return string Slashed string.
873 abstract function strencode( $s );
876 * Set a custom error handler for logging errors during database connection
878 protected function installErrorHandler() {
879 $this->phpError
= false;
880 $this->htmlErrors
= ini_set( 'html_errors', '0' );
881 set_error_handler( [ $this, 'connectionErrorLogger' ] );
885 * Restore the previous error handler and return the last PHP error for this DB
887 * @return bool|string
889 protected function restoreErrorHandler() {
890 restore_error_handler();
891 if ( $this->htmlErrors
!== false ) {
892 ini_set( 'html_errors', $this->htmlErrors
);
895 return $this->getLastPHPError();
899 * @return string|bool Last PHP error for this DB (typically connection errors)
901 protected function getLastPHPError() {
902 if ( $this->phpError
) {
903 $error = preg_replace( '!\[<a.*</a>\]!', '', $this->phpError
);
904 $error = preg_replace( '!^.*?:\s?(.*)$!', '$1', $error );
913 * Error handler for logging errors during database connection
914 * This method should not be used outside of Database classes
917 * @param string $errstr
919 public function connectionErrorLogger( $errno, $errstr ) {
920 $this->phpError
= $errstr;
924 * Create a log context to pass to PSR-3 logger functions.
926 * @param array $extras Additional data to add to context
929 protected function getLogContext( array $extras = [] ) {
932 'db_server' => $this->server
,
933 'db_name' => $this->getDBname(),
934 'db_user' => $this->user
,
940 final public function close() {
941 $exception = null; // error to throw after disconnecting
943 $wasOpen = $this->opened
;
944 // This should mostly do nothing if the connection is already closed
946 // Roll back any dangling transaction first
947 if ( $this->trxLevel
) {
948 if ( $this->trxAtomicLevels
) {
949 // Cannot let incomplete atomic sections be committed
950 $levels = $this->flatAtomicSectionList();
951 $exception = new DBUnexpectedError(
953 __METHOD__
. ": atomic sections $levels are still open."
955 } elseif ( $this->trxAutomatic
) {
956 // Only the connection manager can commit non-empty DBO_TRX transactions
957 // (empty ones we can silently roll back)
958 if ( $this->writesOrCallbacksPending() ) {
959 $exception = new DBUnexpectedError(
962 ": mass commit/rollback of peer transaction required (DBO_TRX set)."
966 // Manual transactions should have been committed or rolled
967 // back, even if empty.
968 $exception = new DBUnexpectedError(
970 __METHOD__
. ": transaction is still open (from {$this->trxFname})."
974 if ( $this->trxEndCallbacksSuppressed
) {
975 $exception = $exception ?
: new DBUnexpectedError(
977 __METHOD__
. ': callbacks are suppressed; cannot properly commit.'
981 // Rollback the changes and run any callbacks as needed
982 $this->rollback( __METHOD__
, self
::FLUSHING_INTERNAL
);
985 // Close the actual connection in the binding handle
986 $closed = $this->closeConnection();
988 $closed = true; // already closed; nothing to do
992 $this->opened
= false;
994 // Throw any unexpected errors after having disconnected
995 if ( $exception instanceof Exception
) {
999 // Note that various subclasses call close() at the start of open(), which itself is
1000 // called by replaceLostConnection(). In that case, just because onTransactionResolution()
1001 // callbacks are pending does not mean that an exception should be thrown. Rather, they
1002 // will be executed after the reconnection step.
1004 // Sanity check that no callbacks are dangling
1005 $fnames = $this->pendingWriteAndCallbackCallers();
1007 throw new RuntimeException(
1008 "Transaction callbacks are still pending:\n" . implode( ', ', $fnames )
1017 * Make sure there is an open connection handle (alive or not) as a sanity check
1019 * This guards against fatal errors to the binding handle not being defined
1020 * in cases where open() was never called or close() was already called
1022 * @throws DBUnexpectedError
1024 protected function assertHasConnectionHandle() {
1025 if ( !$this->isOpen() ) {
1026 throw new DBUnexpectedError( $this, "DB connection was already closed." );
1031 * Make sure that this server is not marked as a replica nor read-only as a sanity check
1033 * @throws DBUnexpectedError
1035 protected function assertIsWritableMaster() {
1036 if ( $this->getLBInfo( 'replica' ) === true ) {
1037 throw new DBUnexpectedError(
1039 'Write operations are not allowed on replica database connections.'
1042 $reason = $this->getReadOnlyReason();
1043 if ( $reason !== false ) {
1044 throw new DBReadOnlyError( $this, "Database is read-only: $reason" );
1049 * Closes underlying database connection
1051 * @return bool Whether connection was closed successfully
1053 abstract protected function closeConnection();
1056 * @deprecated since 1.32
1057 * @param string $error Fallback message, if none is given by DB
1058 * @throws DBConnectionError
1060 public function reportConnectionError( $error = 'Unknown error' ) {
1061 call_user_func( $this->deprecationLogger
, 'Use of ' . __METHOD__
. ' is deprecated.' );
1062 throw new DBConnectionError( $this, $this->lastError() ?
: $error );
1066 * Run a query and return a DBMS-dependent wrapper or boolean
1068 * For SELECT queries, this returns either:
1069 * - a) A driver-specific value/resource, only on success. This can be iterated
1070 * over by calling fetchObject()/fetchRow() until there are no more rows.
1071 * Alternatively, the result can be passed to resultObject() to obtain a
1072 * ResultWrapper instance which can then be iterated over via "foreach".
1073 * - b) False, on any query failure
1075 * For non-SELECT queries, this returns either:
1076 * - a) A driver-specific value/resource, only on success
1077 * - b) True, only on success (e.g. no meaningful result other than "OK")
1078 * - c) False, on any query failure
1080 * @param string $sql SQL query
1081 * @return mixed|bool An object, resource, or true on success; false on failure
1083 abstract protected function doQuery( $sql );
1086 * Determine whether a query writes to the DB. When in doubt, this returns true.
1090 * - Subsequent web requests should not need to wait for replication from
1091 * the master position seen by this web request, unless this request made
1092 * changes to the master. This is handled by ChronologyProtector by checking
1093 * doneWrites() at the end of the request. doneWrites() returns true if any
1094 * query set lastWriteTime; which query() does based on isWriteQuery().
1096 * - Reject write queries to replica DBs, in query().
1098 * @param string $sql
1101 protected function isWriteQuery( $sql ) {
1102 // BEGIN and COMMIT queries are considered read queries here.
1103 // Database backends and drivers (MySQL, MariaDB, php-mysqli) generally
1104 // treat these as write queries, in that their results have "affected rows"
1105 // as meta data as from writes, instead of "num rows" as from reads.
1106 // But, we treat them as read queries because when reading data (from
1107 // either replica or master) we use transactions to enable repeatable-read
1108 // snapshots, which ensures we get consistent results from the same snapshot
1109 // for all queries within a request. Use cases:
1110 // - Treating these as writes would trigger ChronologyProtector (see method doc).
1111 // - We use this method to reject writes to replicas, but we need to allow
1112 // use of transactions on replicas for read snapshots. This fine given
1113 // that transactions by themselves don't make changes, only actual writes
1114 // within the transaction matter, which we still detect.
1116 '/^(?:SELECT|BEGIN|ROLLBACK|COMMIT|SAVEPOINT|RELEASE|SET|SHOW|EXPLAIN|\(SELECT)\b/i',
1122 * @param string $sql
1123 * @return string|null
1125 protected function getQueryVerb( $sql ) {
1126 return preg_match( '/^\s*([a-z]+)/i', $sql, $m ) ?
strtoupper( $m[1] ) : null;
1130 * Determine whether a SQL statement is sensitive to isolation level.
1132 * A SQL statement is considered transactable if its result could vary
1133 * depending on the transaction isolation level. Operational commands
1134 * such as 'SET' and 'SHOW' are not considered to be transactable.
1136 * Main purpose: Used by query() to decide whether to begin a transaction
1137 * before the current query (in DBO_TRX mode, on by default).
1139 * @param string $sql
1142 protected function isTransactableQuery( $sql ) {
1144 $this->getQueryVerb( $sql ),
1145 [ 'BEGIN', 'ROLLBACK', 'COMMIT', 'SET', 'SHOW', 'CREATE', 'ALTER' ],
1151 * @param string $sql A SQL query
1152 * @param bool $pseudoPermanent Treat any table from CREATE TEMPORARY as pseudo-permanent
1153 * @return int|null A self::TEMP_* constant for temp table operations or null otherwise
1155 protected function registerTempTableWrite( $sql, $pseudoPermanent ) {
1156 static $qt = '[`"\']?(\w+)[`"\']?'; // quoted table
1159 '/^CREATE\s+TEMPORARY\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?' . $qt . '/i',
1163 $type = $pseudoPermanent ? self
::TEMP_PSEUDO_PERMANENT
: self
::TEMP_NORMAL
;
1164 $this->sessionTempTables
[$matches[1]] = $type;
1167 } elseif ( preg_match(
1168 '/^DROP\s+(?:TEMPORARY\s+)?TABLE\s+(?:IF\s+EXISTS\s+)?' . $qt . '/i',
1172 $type = $this->sessionTempTables
[$matches[1]] ??
null;
1173 unset( $this->sessionTempTables
[$matches[1]] );
1176 } elseif ( preg_match(
1177 '/^TRUNCATE\s+(?:TEMPORARY\s+)?TABLE\s+(?:IF\s+EXISTS\s+)?' . $qt . '/i',
1181 return $this->sessionTempTables
[$matches[1]] ??
null;
1182 } elseif ( preg_match(
1183 '/^(?:(?:INSERT|REPLACE)\s+(?:\w+\s+)?INTO|UPDATE|DELETE\s+FROM)\s+' . $qt . '/i',
1187 return $this->sessionTempTables
[$matches[1]] ??
null;
1193 public function query( $sql, $fname = __METHOD__
, $flags = 0 ) {
1194 $this->assertTransactionStatus( $sql, $fname );
1195 $this->assertHasConnectionHandle();
1197 $flags = (int)$flags; // b/c; this field used to be a bool
1198 $ignoreErrors = $this->hasFlags( $flags, self
::QUERY_SILENCE_ERRORS
);
1199 $pseudoPermanent = $this->hasFlags( $flags, self
::QUERY_PSEUDO_PERMANENT
);
1201 $priorTransaction = $this->trxLevel
;
1202 $priorWritesPending = $this->writesOrCallbacksPending();
1203 $this->lastQuery
= $sql;
1205 if ( $this->isWriteQuery( $sql ) ) {
1206 # In theory, non-persistent writes are allowed in read-only mode, but due to things
1207 # like https://bugs.mysql.com/bug.php?id=33669 that might not work anyway...
1208 $this->assertIsWritableMaster();
1209 # Do not treat temporary table writes as "meaningful writes" that need committing.
1210 # Profile them as reads. Integration tests can override this behavior via $flags.
1211 $tableType = $this->registerTempTableWrite( $sql, $pseudoPermanent );
1212 $isEffectiveWrite = ( $tableType !== self
::TEMP_NORMAL
);
1214 $isEffectiveWrite = false;
1217 # Add trace comment to the begin of the sql string, right after the operator.
1218 # Or, for one-word queries (like "BEGIN" or COMMIT") add it to the end (T44598)
1219 $commentedSql = preg_replace( '/\s|$/', " /* $fname {$this->agent} */ ", $sql, 1 );
1221 # Send the query to the server and fetch any corresponding errors
1222 $ret = $this->attemptQuery( $sql, $commentedSql, $isEffectiveWrite, $fname );
1223 $lastError = $this->lastError();
1224 $lastErrno = $this->lastErrno();
1226 $recoverableSR = false; // recoverable statement rollback?
1227 $recoverableCL = false; // recoverable connection loss?
1229 if ( $ret === false && $this->wasConnectionLoss() ) {
1230 # Check if no meaningful session state was lost
1231 $recoverableCL = $this->canRecoverFromDisconnect( $sql, $priorWritesPending );
1232 # Update session state tracking and try to restore the connection
1233 $reconnected = $this->replaceLostConnection( __METHOD__
);
1234 # Silently resend the query to the server if it is safe and possible
1235 if ( $recoverableCL && $reconnected ) {
1236 $ret = $this->attemptQuery( $sql, $commentedSql, $isEffectiveWrite, $fname );
1237 $lastError = $this->lastError();
1238 $lastErrno = $this->lastErrno();
1240 if ( $ret === false && $this->wasConnectionLoss() ) {
1241 # Query probably causes disconnects; reconnect and do not re-run it
1242 $this->replaceLostConnection( __METHOD__
);
1244 $recoverableCL = false; // connection does not need recovering
1245 $recoverableSR = $this->wasKnownStatementRollbackError();
1249 $recoverableSR = $this->wasKnownStatementRollbackError();
1252 if ( $ret === false ) {
1253 if ( $priorTransaction ) {
1254 if ( $recoverableSR ) {
1255 # We're ignoring an error that caused just the current query to be aborted.
1256 # But log the cause so we can log a deprecation notice if a caller actually
1258 $this->trxStatusIgnoredCause
= [ $lastError, $lastErrno, $fname ];
1259 } elseif ( !$recoverableCL ) {
1260 # Either the query was aborted or all queries after BEGIN where aborted.
1261 # In the first case, the only options going forward are (a) ROLLBACK, or
1262 # (b) ROLLBACK TO SAVEPOINT (if one was set). If the later case, the only
1263 # option is ROLLBACK, since the snapshots would have been released.
1264 $this->trxStatus
= self
::STATUS_TRX_ERROR
;
1265 $this->trxStatusCause
=
1266 $this->getQueryExceptionAndLog( $lastError, $lastErrno, $sql, $fname );
1267 $ignoreErrors = false; // cannot recover
1268 $this->trxStatusIgnoredCause
= null;
1272 $this->reportQueryError( $lastError, $lastErrno, $sql, $fname, $ignoreErrors );
1275 return $this->resultObject( $ret );
1279 * Wrapper for query() that also handles profiling, logging, and affected row count updates
1281 * @param string $sql Original SQL query
1282 * @param string $commentedSql SQL query with debugging/trace comment
1283 * @param bool $isEffectiveWrite Whether the query is a (non-temporary table) write
1284 * @param string $fname Name of the calling function
1285 * @return bool|ResultWrapper True for a successful write query, ResultWrapper
1286 * object for a successful read query, or false on failure
1288 private function attemptQuery( $sql, $commentedSql, $isEffectiveWrite, $fname ) {
1289 $this->beginIfImplied( $sql, $fname );
1291 # Keep track of whether the transaction has write queries pending
1292 if ( $isEffectiveWrite ) {
1293 $this->lastWriteTime
= microtime( true );
1294 if ( $this->trxLevel
&& !$this->trxDoneWrites
) {
1295 $this->trxDoneWrites
= true;
1296 $this->trxProfiler
->transactionWritingIn(
1297 $this->server
, $this->getDomainID(), $this->trxShortId
);
1301 if ( $this->getFlag( self
::DBO_DEBUG
) ) {
1302 $this->queryLogger
->debug( "{$this->getDomainID()} {$commentedSql}" );
1305 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
1306 # generalizeSQL() will probably cut down the query to reasonable
1307 # logging size most of the time. The substr is really just a sanity check.
1309 $queryProf = 'query-m: ' . substr( self
::generalizeSQL( $sql ), 0, 255 );
1311 $queryProf = 'query: ' . substr( self
::generalizeSQL( $sql ), 0, 255 );
1314 # Include query transaction state
1315 $queryProf .= $this->trxShortId ?
" [TRX#{$this->trxShortId}]" : "";
1317 $startTime = microtime( true );
1318 $ps = $this->profiler ?
( $this->profiler
)( $queryProf ) : null;
1319 $this->affectedRowCount
= null;
1320 $ret = $this->doQuery( $commentedSql );
1321 $this->affectedRowCount
= $this->affectedRows();
1322 unset( $ps ); // profile out (if set)
1323 $queryRuntime = max( microtime( true ) - $startTime, 0.0 );
1325 if ( $ret !== false ) {
1326 $this->lastPing
= $startTime;
1327 if ( $isEffectiveWrite && $this->trxLevel
) {
1328 $this->updateTrxWriteQueryTime( $sql, $queryRuntime, $this->affectedRows() );
1329 $this->trxWriteCallers
[] = $fname;
1333 if ( $sql === self
::PING_QUERY
) {
1334 $this->rttEstimate
= $queryRuntime;
1337 $this->trxProfiler
->recordQueryCompletion(
1341 $isEffectiveWrite ?
$this->affectedRows() : $this->numRows( $ret )
1343 $this->queryLogger
->debug( $sql, [
1345 'master' => $isMaster,
1346 'runtime' => $queryRuntime,
1353 * Start an implicit transaction if DBO_TRX is enabled and no transaction is active
1355 * @param string $sql
1356 * @param string $fname
1358 private function beginIfImplied( $sql, $fname ) {
1361 $this->getFlag( self
::DBO_TRX
) &&
1362 $this->isTransactableQuery( $sql )
1364 $this->begin( __METHOD__
. " ($fname)", self
::TRANSACTION_INTERNAL
);
1365 $this->trxAutomatic
= true;
1370 * Update the estimated run-time of a query, not counting large row lock times
1372 * LoadBalancer can be set to rollback transactions that will create huge replication
1373 * lag. It bases this estimate off of pendingWriteQueryDuration(). Certain simple
1374 * queries, like inserting a row can take a long time due to row locking. This method
1375 * uses some simple heuristics to discount those cases.
1377 * @param string $sql A SQL write query
1378 * @param float $runtime Total runtime, including RTT
1379 * @param int $affected Affected row count
1381 private function updateTrxWriteQueryTime( $sql, $runtime, $affected ) {
1382 // Whether this is indicative of replica DB runtime (except for RBR or ws_repl)
1383 $indicativeOfReplicaRuntime = true;
1384 if ( $runtime > self
::SLOW_WRITE_SEC
) {
1385 $verb = $this->getQueryVerb( $sql );
1386 // insert(), upsert(), replace() are fast unless bulky in size or blocked on locks
1387 if ( $verb === 'INSERT' ) {
1388 $indicativeOfReplicaRuntime = $this->affectedRows() > self
::SMALL_WRITE_ROWS
;
1389 } elseif ( $verb === 'REPLACE' ) {
1390 $indicativeOfReplicaRuntime = $this->affectedRows() > self
::SMALL_WRITE_ROWS
/ 2;
1394 $this->trxWriteDuration +
= $runtime;
1395 $this->trxWriteQueryCount +
= 1;
1396 $this->trxWriteAffectedRows +
= $affected;
1397 if ( $indicativeOfReplicaRuntime ) {
1398 $this->trxWriteAdjDuration +
= $runtime;
1399 $this->trxWriteAdjQueryCount +
= 1;
1404 * Error out if the DB is not in a valid state for a query via query()
1406 * @param string $sql
1407 * @param string $fname
1408 * @throws DBTransactionStateError
1410 private function assertTransactionStatus( $sql, $fname ) {
1411 $verb = $this->getQueryVerb( $sql );
1412 if ( $verb === 'USE' ) {
1413 throw new DBUnexpectedError( $this, "Got USE query; use selectDomain() instead." );
1416 if ( $verb === 'ROLLBACK' ) { // transaction/savepoint
1420 if ( $this->trxStatus
< self
::STATUS_TRX_OK
) {
1421 throw new DBTransactionStateError(
1423 "Cannot execute query from $fname while transaction status is ERROR.",
1425 $this->trxStatusCause
1427 } elseif ( $this->trxStatus
=== self
::STATUS_TRX_OK
&& $this->trxStatusIgnoredCause
) {
1428 list( $iLastError, $iLastErrno, $iFname ) = $this->trxStatusIgnoredCause
;
1429 call_user_func( $this->deprecationLogger
,
1430 "Caller from $fname ignored an error originally raised from $iFname: " .
1431 "[$iLastErrno] $iLastError"
1433 $this->trxStatusIgnoredCause
= null;
1437 public function assertNoOpenTransactions() {
1438 if ( $this->explicitTrxActive() ) {
1439 throw new DBTransactionError(
1441 "Explicit transaction still active. A caller may have caught an error. "
1442 . "Open transactions: " . $this->flatAtomicSectionList()
1448 * Determine whether it is safe to retry queries after a database connection is lost
1450 * @param string $sql SQL query
1451 * @param bool $priorWritesPending Whether there is a transaction open with
1452 * possible write queries or transaction pre-commit/idle callbacks
1453 * waiting on it to finish.
1454 * @return bool True if it is safe to retry the query, false otherwise
1456 private function canRecoverFromDisconnect( $sql, $priorWritesPending ) {
1457 # Transaction dropped; this can mean lost writes, or REPEATABLE-READ snapshots.
1458 # Dropped connections also mean that named locks are automatically released.
1459 # Only allow error suppression in autocommit mode or when the lost transaction
1460 # didn't matter anyway (aside from DBO_TRX snapshot loss).
1461 if ( $this->namedLocksHeld
) {
1462 return false; // possible critical section violation
1463 } elseif ( $this->sessionTempTables
) {
1464 return false; // tables might be queried latter
1465 } elseif ( $sql === 'COMMIT' ) {
1466 return !$priorWritesPending; // nothing written anyway? (T127428)
1467 } elseif ( $sql === 'ROLLBACK' ) {
1468 return true; // transaction lost...which is also what was requested :)
1469 } elseif ( $this->explicitTrxActive() ) {
1470 return false; // don't drop atomocity and explicit snapshots
1471 } elseif ( $priorWritesPending ) {
1472 return false; // prior writes lost from implicit transaction
1479 * Clean things up after session (and thus transaction) loss before reconnect
1481 private function handleSessionLossPreconnect() {
1482 // Clean up tracking of session-level things...
1483 // https://dev.mysql.com/doc/refman/5.7/en/implicit-commit.html
1484 // https://www.postgresql.org/docs/9.2/static/sql-createtable.html (ignoring ON COMMIT)
1485 $this->sessionTempTables
= [];
1486 // https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html#function_get-lock
1487 // https://www.postgresql.org/docs/9.4/static/functions-admin.html#FUNCTIONS-ADVISORY-LOCKS
1488 $this->namedLocksHeld
= [];
1489 // Session loss implies transaction loss
1490 $this->trxLevel
= 0;
1491 $this->trxAtomicCounter
= 0;
1492 $this->trxIdleCallbacks
= []; // T67263; transaction already lost
1493 $this->trxPreCommitCallbacks
= []; // T67263; transaction already lost
1494 // @note: leave trxRecurringCallbacks in place
1495 if ( $this->trxDoneWrites
) {
1496 $this->trxProfiler
->transactionWritingOut(
1498 $this->getDomainID(),
1500 $this->pendingWriteQueryDuration( self
::ESTIMATE_TOTAL
),
1501 $this->trxWriteAffectedRows
1507 * Clean things up after session (and thus transaction) loss after reconnect
1509 private function handleSessionLossPostconnect() {
1511 // Handle callbacks in trxEndCallbacks, e.g. onTransactionResolution().
1512 // If callback suppression is set then the array will remain unhandled.
1513 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_ROLLBACK
);
1514 } catch ( Exception
$ex ) {
1515 // Already logged; move on...
1518 // Handle callbacks in trxRecurringCallbacks, e.g. setTransactionListener()
1519 $this->runTransactionListenerCallbacks( self
::TRIGGER_ROLLBACK
);
1520 } catch ( Exception
$ex ) {
1521 // Already logged; move on...
1526 * Checks whether the cause of the error is detected to be a timeout.
1528 * It returns false by default, and not all engines support detecting this yet.
1529 * If this returns false, it will be treated as a generic query error.
1531 * @param string $error Error text
1532 * @param int $errno Error number
1535 protected function wasQueryTimeout( $error, $errno ) {
1540 * Report a query error. Log the error, and if neither the object ignore
1541 * flag nor the $ignoreErrors flag is set, throw a DBQueryError.
1543 * @param string $error
1545 * @param string $sql
1546 * @param string $fname
1547 * @param bool $ignoreErrors
1548 * @throws DBQueryError
1550 public function reportQueryError( $error, $errno, $sql, $fname, $ignoreErrors = false ) {
1551 if ( $ignoreErrors ) {
1552 $this->queryLogger
->debug( "SQL ERROR (ignored): $error\n" );
1554 $exception = $this->getQueryExceptionAndLog( $error, $errno, $sql, $fname );
1561 * @param string $error
1562 * @param string|int $errno
1563 * @param string $sql
1564 * @param string $fname
1567 private function getQueryExceptionAndLog( $error, $errno, $sql, $fname ) {
1568 $sql1line = mb_substr( str_replace( "\n", "\\n", $sql ), 0, 5 * 1024 );
1569 $this->queryLogger
->error(
1570 "{fname}\t{db_server}\t{errno}\t{error}\t{sql1line}",
1571 $this->getLogContext( [
1572 'method' => __METHOD__
,
1575 'sql1line' => $sql1line,
1577 'trace' => ( new RuntimeException() )->getTraceAsString()
1580 $this->queryLogger
->debug( "SQL ERROR: " . $error . "\n" );
1581 $wasQueryTimeout = $this->wasQueryTimeout( $error, $errno );
1582 if ( $wasQueryTimeout ) {
1583 $e = new DBQueryTimeoutError( $this, $error, $errno, $sql, $fname );
1585 $e = new DBQueryError( $this, $error, $errno, $sql, $fname );
1591 public function freeResult( $res ) {
1594 public function selectField(
1595 $table, $var, $cond = '', $fname = __METHOD__
, $options = [], $join_conds = []
1597 if ( $var === '*' ) { // sanity
1598 throw new DBUnexpectedError( $this, "Cannot use a * field: got '$var'" );
1601 if ( !is_array( $options ) ) {
1602 $options = [ $options ];
1605 $options['LIMIT'] = 1;
1607 $res = $this->select( $table, $var, $cond, $fname, $options, $join_conds );
1608 if ( $res === false ||
!$this->numRows( $res ) ) {
1612 $row = $this->fetchRow( $res );
1614 if ( $row !== false ) {
1615 return reset( $row );
1621 public function selectFieldValues(
1622 $table, $var, $cond = '', $fname = __METHOD__
, $options = [], $join_conds = []
1624 if ( $var === '*' ) { // sanity
1625 throw new DBUnexpectedError( $this, "Cannot use a * field" );
1626 } elseif ( !is_string( $var ) ) { // sanity
1627 throw new DBUnexpectedError( $this, "Cannot use an array of fields" );
1630 if ( !is_array( $options ) ) {
1631 $options = [ $options ];
1634 $res = $this->select( $table, [ 'value' => $var ], $cond, $fname, $options, $join_conds );
1635 if ( $res === false ) {
1640 foreach ( $res as $row ) {
1641 $values[] = $row->value
;
1648 * Returns an optional USE INDEX clause to go after the table, and a
1649 * string to go at the end of the query.
1651 * @param array $options Associative array of options to be turned into
1652 * an SQL query, valid keys are listed in the function.
1654 * @see Database::select()
1656 protected function makeSelectOptions( $options ) {
1657 $preLimitTail = $postLimitTail = '';
1662 foreach ( $options as $key => $option ) {
1663 if ( is_numeric( $key ) ) {
1664 $noKeyOptions[$option] = true;
1668 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1670 $preLimitTail .= $this->makeOrderBy( $options );
1672 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1673 $postLimitTail .= ' FOR UPDATE';
1676 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1677 $postLimitTail .= ' LOCK IN SHARE MODE';
1680 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1681 $startOpts .= 'DISTINCT';
1684 # Various MySQL extensions
1685 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
1686 $startOpts .= ' /*! STRAIGHT_JOIN */';
1689 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) {
1690 $startOpts .= ' HIGH_PRIORITY';
1693 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
1694 $startOpts .= ' SQL_BIG_RESULT';
1697 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
1698 $startOpts .= ' SQL_BUFFER_RESULT';
1701 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
1702 $startOpts .= ' SQL_SMALL_RESULT';
1705 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
1706 $startOpts .= ' SQL_CALC_FOUND_ROWS';
1709 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) {
1710 $startOpts .= ' SQL_CACHE';
1713 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) {
1714 $startOpts .= ' SQL_NO_CACHE';
1717 if ( isset( $options['USE INDEX'] ) && is_string( $options['USE INDEX'] ) ) {
1718 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1722 if ( isset( $options['IGNORE INDEX'] ) && is_string( $options['IGNORE INDEX'] ) ) {
1723 $ignoreIndex = $this->ignoreIndexClause( $options['IGNORE INDEX'] );
1728 return [ $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ];
1732 * Returns an optional GROUP BY with an optional HAVING
1734 * @param array $options Associative array of options
1736 * @see Database::select()
1739 protected function makeGroupByWithHaving( $options ) {
1741 if ( isset( $options['GROUP BY'] ) ) {
1742 $gb = is_array( $options['GROUP BY'] )
1743 ?
implode( ',', $options['GROUP BY'] )
1744 : $options['GROUP BY'];
1745 $sql .= ' GROUP BY ' . $gb;
1747 if ( isset( $options['HAVING'] ) ) {
1748 $having = is_array( $options['HAVING'] )
1749 ?
$this->makeList( $options['HAVING'], self
::LIST_AND
)
1750 : $options['HAVING'];
1751 $sql .= ' HAVING ' . $having;
1758 * Returns an optional ORDER BY
1760 * @param array $options Associative array of options
1762 * @see Database::select()
1765 protected function makeOrderBy( $options ) {
1766 if ( isset( $options['ORDER BY'] ) ) {
1767 $ob = is_array( $options['ORDER BY'] )
1768 ?
implode( ',', $options['ORDER BY'] )
1769 : $options['ORDER BY'];
1771 return ' ORDER BY ' . $ob;
1777 public function select(
1778 $table, $vars, $conds = '', $fname = __METHOD__
, $options = [], $join_conds = []
1780 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1782 return $this->query( $sql, $fname );
1785 public function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__
,
1786 $options = [], $join_conds = []
1788 if ( is_array( $vars ) ) {
1789 $fields = implode( ',', $this->fieldNamesWithAlias( $vars ) );
1794 $options = (array)$options;
1795 $useIndexes = ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1796 ?
$options['USE INDEX']
1799 isset( $options['IGNORE INDEX'] ) &&
1800 is_array( $options['IGNORE INDEX'] )
1802 ?
$options['IGNORE INDEX']
1806 $this->selectOptionsIncludeLocking( $options ) &&
1807 $this->selectFieldsOrOptionsAggregate( $vars, $options )
1809 // Some DB types (postgres/oracle) disallow FOR UPDATE with aggregate
1810 // functions. Discourage use of such queries to encourage compatibility.
1812 $this->deprecationLogger
,
1813 __METHOD__
. ": aggregation used with a locking SELECT ($fname)."
1817 if ( is_array( $table ) ) {
1819 $this->tableNamesWithIndexClauseOrJOIN(
1820 $table, $useIndexes, $ignoreIndexes, $join_conds );
1821 } elseif ( $table != '' ) {
1823 $this->tableNamesWithIndexClauseOrJOIN(
1824 [ $table ], $useIndexes, $ignoreIndexes, [] );
1829 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ) =
1830 $this->makeSelectOptions( $options );
1832 if ( is_array( $conds ) ) {
1833 $conds = $this->makeList( $conds, self
::LIST_AND
);
1836 if ( $conds === null ||
$conds === false ) {
1837 $this->queryLogger
->warning(
1841 . ' with incorrect parameters: $conds must be a string or an array'
1846 if ( $conds === '' ||
$conds === '*' ) {
1847 $sql = "SELECT $startOpts $fields $from $useIndex $ignoreIndex $preLimitTail";
1848 } elseif ( is_string( $conds ) ) {
1849 $sql = "SELECT $startOpts $fields $from $useIndex $ignoreIndex " .
1850 "WHERE $conds $preLimitTail";
1852 throw new DBUnexpectedError( $this, __METHOD__
. ' called with incorrect parameters' );
1855 if ( isset( $options['LIMIT'] ) ) {
1856 $sql = $this->limitResult( $sql, $options['LIMIT'],
1857 $options['OFFSET'] ??
false );
1859 $sql = "$sql $postLimitTail";
1861 if ( isset( $options['EXPLAIN'] ) ) {
1862 $sql = 'EXPLAIN ' . $sql;
1868 public function selectRow( $table, $vars, $conds, $fname = __METHOD__
,
1869 $options = [], $join_conds = []
1871 $options = (array)$options;
1872 $options['LIMIT'] = 1;
1873 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1875 if ( $res === false ) {
1879 if ( !$this->numRows( $res ) ) {
1883 $obj = $this->fetchObject( $res );
1888 public function estimateRowCount(
1889 $table, $var = '*', $conds = '', $fname = __METHOD__
, $options = [], $join_conds = []
1891 $conds = $this->normalizeConditions( $conds, $fname );
1892 $column = $this->extractSingleFieldFromList( $var );
1893 if ( is_string( $column ) && !in_array( $column, [ '*', '1' ] ) ) {
1894 $conds[] = "$column IS NOT NULL";
1897 $res = $this->select(
1898 $table, [ 'rowcount' => 'COUNT(*)' ], $conds, $fname, $options, $join_conds
1900 $row = $res ?
$this->fetchRow( $res ) : [];
1902 return isset( $row['rowcount'] ) ?
(int)$row['rowcount'] : 0;
1905 public function selectRowCount(
1906 $tables, $var = '*', $conds = '', $fname = __METHOD__
, $options = [], $join_conds = []
1908 $conds = $this->normalizeConditions( $conds, $fname );
1909 $column = $this->extractSingleFieldFromList( $var );
1910 if ( is_string( $column ) && !in_array( $column, [ '*', '1' ] ) ) {
1911 $conds[] = "$column IS NOT NULL";
1914 $res = $this->select(
1916 'tmp_count' => $this->buildSelectSubquery(
1925 [ 'rowcount' => 'COUNT(*)' ],
1929 $row = $res ?
$this->fetchRow( $res ) : [];
1931 return isset( $row['rowcount'] ) ?
(int)$row['rowcount'] : 0;
1935 * @param string|array $options
1938 private function selectOptionsIncludeLocking( $options ) {
1939 $options = (array)$options;
1940 foreach ( [ 'FOR UPDATE', 'LOCK IN SHARE MODE' ] as $lock ) {
1941 if ( in_array( $lock, $options, true ) ) {
1950 * @param array|string $fields
1951 * @param array|string $options
1954 private function selectFieldsOrOptionsAggregate( $fields, $options ) {
1955 foreach ( (array)$options as $key => $value ) {
1956 if ( is_string( $key ) ) {
1957 if ( preg_match( '/^(?:GROUP BY|HAVING)$/i', $key ) ) {
1960 } elseif ( is_string( $value ) ) {
1961 if ( preg_match( '/^(?:DISTINCT|DISTINCTROW)$/i', $value ) ) {
1967 $regex = '/^(?:COUNT|MIN|MAX|SUM|GROUP_CONCAT|LISTAGG|ARRAY_AGG)\s*\\(/i';
1968 foreach ( (array)$fields as $field ) {
1969 if ( is_string( $field ) && preg_match( $regex, $field ) ) {
1978 * @param array|string $conds
1979 * @param string $fname
1982 final protected function normalizeConditions( $conds, $fname ) {
1983 if ( $conds === null ||
$conds === false ) {
1984 $this->queryLogger
->warning(
1988 . ' with incorrect parameters: $conds must be a string or an array'
1993 if ( !is_array( $conds ) ) {
1994 $conds = ( $conds === '' ) ?
[] : [ $conds ];
2001 * @param array|string $var Field parameter in the style of select()
2002 * @return string|null Column name or null; ignores aliases
2003 * @throws DBUnexpectedError Errors out if multiple columns are given
2005 final protected function extractSingleFieldFromList( $var ) {
2006 if ( is_array( $var ) ) {
2009 } elseif ( count( $var ) == 1 ) {
2010 $column = $var[0] ??
reset( $var );
2012 throw new DBUnexpectedError( $this, __METHOD__
. ': got multiple columns.' );
2021 public function lockForUpdate(
2022 $table, $conds = '', $fname = __METHOD__
, $options = [], $join_conds = []
2024 if ( !$this->trxLevel
&& !$this->getFlag( self
::DBO_TRX
) ) {
2025 throw new DBUnexpectedError(
2027 __METHOD__
. ': no transaction is active nor is DBO_TRX set'
2031 $options = (array)$options;
2032 $options[] = 'FOR UPDATE';
2034 return $this->selectRowCount( $table, '*', $conds, $fname, $options, $join_conds );
2038 * Removes most variables from an SQL query and replaces them with X or N for numbers.
2039 * It's only slightly flawed. Don't use for anything important.
2041 * @param string $sql A SQL Query
2045 protected static function generalizeSQL( $sql ) {
2046 # This does the same as the regexp below would do, but in such a way
2047 # as to avoid crashing php on some large strings.
2048 # $sql = preg_replace( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql );
2050 $sql = str_replace( "\\\\", '', $sql );
2051 $sql = str_replace( "\\'", '', $sql );
2052 $sql = str_replace( "\\\"", '', $sql );
2053 $sql = preg_replace( "/'.*'/s", "'X'", $sql );
2054 $sql = preg_replace( '/".*"/s', "'X'", $sql );
2056 # All newlines, tabs, etc replaced by single space
2057 $sql = preg_replace( '/\s+/', ' ', $sql );
2060 # except the ones surrounded by characters, e.g. l10n
2061 $sql = preg_replace( '/-?\d+(,-?\d+)+/s', 'N,...,N', $sql );
2062 $sql = preg_replace( '/(?<![a-zA-Z])-?\d+(?![a-zA-Z])/s', 'N', $sql );
2067 public function fieldExists( $table, $field, $fname = __METHOD__
) {
2068 $info = $this->fieldInfo( $table, $field );
2073 public function indexExists( $table, $index, $fname = __METHOD__
) {
2074 if ( !$this->tableExists( $table ) ) {
2078 $info = $this->indexInfo( $table, $index, $fname );
2079 if ( is_null( $info ) ) {
2082 return $info !== false;
2086 abstract public function tableExists( $table, $fname = __METHOD__
);
2088 public function indexUnique( $table, $index ) {
2089 $indexInfo = $this->indexInfo( $table, $index );
2091 if ( !$indexInfo ) {
2095 return !$indexInfo[0]->Non_unique
;
2099 * Helper for Database::insert().
2101 * @param array $options
2104 protected function makeInsertOptions( $options ) {
2105 return implode( ' ', $options );
2108 public function insert( $table, $a, $fname = __METHOD__
, $options = [] ) {
2109 # No rows to insert, easy just return now
2110 if ( !count( $a ) ) {
2114 $table = $this->tableName( $table );
2116 if ( !is_array( $options ) ) {
2117 $options = [ $options ];
2120 $options = $this->makeInsertOptions( $options );
2122 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
2124 $keys = array_keys( $a[0] );
2127 $keys = array_keys( $a );
2130 $sql = 'INSERT ' . $options .
2131 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
2135 foreach ( $a as $row ) {
2141 $sql .= '(' . $this->makeList( $row ) . ')';
2144 $sql .= '(' . $this->makeList( $a ) . ')';
2147 $this->query( $sql, $fname );
2153 * Make UPDATE options array for Database::makeUpdateOptions
2155 * @param array $options
2158 protected function makeUpdateOptionsArray( $options ) {
2159 if ( !is_array( $options ) ) {
2160 $options = [ $options ];
2165 if ( in_array( 'IGNORE', $options ) ) {
2173 * Make UPDATE options for the Database::update function
2175 * @param array $options The options passed to Database::update
2178 protected function makeUpdateOptions( $options ) {
2179 $opts = $this->makeUpdateOptionsArray( $options );
2181 return implode( ' ', $opts );
2184 public function update( $table, $values, $conds, $fname = __METHOD__
, $options = [] ) {
2185 $table = $this->tableName( $table );
2186 $opts = $this->makeUpdateOptions( $options );
2187 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, self
::LIST_SET
);
2189 if ( $conds !== [] && $conds !== '*' ) {
2190 $sql .= " WHERE " . $this->makeList( $conds, self
::LIST_AND
);
2193 $this->query( $sql, $fname );
2198 public function makeList( $a, $mode = self
::LIST_COMMA
) {
2199 if ( !is_array( $a ) ) {
2200 throw new DBUnexpectedError( $this, __METHOD__
. ' called with incorrect parameters' );
2206 foreach ( $a as $field => $value ) {
2208 if ( $mode == self
::LIST_AND
) {
2210 } elseif ( $mode == self
::LIST_OR
) {
2219 if ( ( $mode == self
::LIST_AND ||
$mode == self
::LIST_OR
) && is_numeric( $field ) ) {
2220 $list .= "($value)";
2221 } elseif ( $mode == self
::LIST_SET
&& is_numeric( $field ) ) {
2224 ( $mode == self
::LIST_AND ||
$mode == self
::LIST_OR
) && is_array( $value )
2226 // Remove null from array to be handled separately if found
2227 $includeNull = false;
2228 foreach ( array_keys( $value, null, true ) as $nullKey ) {
2229 $includeNull = true;
2230 unset( $value[$nullKey] );
2232 if ( count( $value ) == 0 && !$includeNull ) {
2233 throw new InvalidArgumentException(
2234 __METHOD__
. ": empty input for field $field" );
2235 } elseif ( count( $value ) == 0 ) {
2236 // only check if $field is null
2237 $list .= "$field IS NULL";
2239 // IN clause contains at least one valid element
2240 if ( $includeNull ) {
2241 // Group subconditions to ensure correct precedence
2244 if ( count( $value ) == 1 ) {
2245 // Special-case single values, as IN isn't terribly efficient
2246 // Don't necessarily assume the single key is 0; we don't
2247 // enforce linear numeric ordering on other arrays here.
2248 $value = array_values( $value )[0];
2249 $list .= $field . " = " . $this->addQuotes( $value );
2251 $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
2253 // if null present in array, append IS NULL
2254 if ( $includeNull ) {
2255 $list .= " OR $field IS NULL)";
2258 } elseif ( $value === null ) {
2259 if ( $mode == self
::LIST_AND ||
$mode == self
::LIST_OR
) {
2260 $list .= "$field IS ";
2261 } elseif ( $mode == self
::LIST_SET
) {
2262 $list .= "$field = ";
2267 $mode == self
::LIST_AND ||
$mode == self
::LIST_OR ||
$mode == self
::LIST_SET
2269 $list .= "$field = ";
2271 $list .= $mode == self
::LIST_NAMES ?
$value : $this->addQuotes( $value );
2278 public function makeWhereFrom2d( $data, $baseKey, $subKey ) {
2281 foreach ( $data as $base => $sub ) {
2282 if ( count( $sub ) ) {
2283 $conds[] = $this->makeList(
2284 [ $baseKey => $base, $subKey => array_keys( $sub ) ],
2290 return $this->makeList( $conds, self
::LIST_OR
);
2292 // Nothing to search for...
2297 public function aggregateValue( $valuedata, $valuename = 'value' ) {
2301 public function bitNot( $field ) {
2305 public function bitAnd( $fieldLeft, $fieldRight ) {
2306 return "($fieldLeft & $fieldRight)";
2309 public function bitOr( $fieldLeft, $fieldRight ) {
2310 return "($fieldLeft | $fieldRight)";
2313 public function buildConcat( $stringList ) {
2314 return 'CONCAT(' . implode( ',', $stringList ) . ')';
2317 public function buildGroupConcatField(
2318 $delim, $table, $field, $conds = '', $join_conds = []
2320 $fld = "GROUP_CONCAT($field SEPARATOR " . $this->addQuotes( $delim ) . ')';
2322 return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
2325 public function buildSubstring( $input, $startPosition, $length = null ) {
2326 $this->assertBuildSubstringParams( $startPosition, $length );
2327 $functionBody = "$input FROM $startPosition";
2328 if ( $length !== null ) {
2329 $functionBody .= " FOR $length";
2331 return 'SUBSTRING(' . $functionBody . ')';
2335 * Check type and bounds for parameters to self::buildSubstring()
2337 * All supported databases have substring functions that behave the same for
2338 * positive $startPosition and non-negative $length, but behaviors differ when
2339 * given 0 or negative $startPosition or negative $length. The simplest
2340 * solution to that is to just forbid those values.
2342 * @param int $startPosition
2343 * @param int|null $length
2346 protected function assertBuildSubstringParams( $startPosition, $length ) {
2347 if ( !is_int( $startPosition ) ||
$startPosition <= 0 ) {
2348 throw new InvalidArgumentException(
2349 '$startPosition must be a positive integer'
2352 if ( !( is_int( $length ) && $length >= 0 ||
$length === null ) ) {
2353 throw new InvalidArgumentException(
2354 '$length must be null or an integer greater than or equal to 0'
2359 public function buildStringCast( $field ) {
2360 // In theory this should work for any standards-compliant
2361 // SQL implementation, although it may not be the best way to do it.
2362 return "CAST( $field AS CHARACTER )";
2365 public function buildIntegerCast( $field ) {
2366 return 'CAST( ' . $field . ' AS INTEGER )';
2369 public function buildSelectSubquery(
2370 $table, $vars, $conds = '', $fname = __METHOD__
,
2371 $options = [], $join_conds = []
2373 return new Subquery(
2374 $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds )
2378 public function databasesAreIndependent() {
2382 final public function selectDB( $db ) {
2383 $this->selectDomain( new DatabaseDomain(
2385 $this->currentDomain
->getSchema(),
2386 $this->currentDomain
->getTablePrefix()
2392 final public function selectDomain( $domain ) {
2393 $this->doSelectDomain( DatabaseDomain
::newFromId( $domain ) );
2396 protected function doSelectDomain( DatabaseDomain
$domain ) {
2397 $this->currentDomain
= $domain;
2400 public function getDBname() {
2401 return $this->currentDomain
->getDatabase();
2404 public function getServer() {
2405 return $this->server
;
2408 public function tableName( $name, $format = 'quoted' ) {
2409 if ( $name instanceof Subquery
) {
2410 throw new DBUnexpectedError(
2412 __METHOD__
. ': got Subquery instance when expecting a string.'
2416 # Skip the entire process when we have a string quoted on both ends.
2417 # Note that we check the end so that we will still quote any use of
2418 # use of `database`.table. But won't break things if someone wants
2419 # to query a database table with a dot in the name.
2420 if ( $this->isQuotedIdentifier( $name ) ) {
2424 # Lets test for any bits of text that should never show up in a table
2425 # name. Basically anything like JOIN or ON which are actually part of
2426 # SQL queries, but may end up inside of the table value to combine
2427 # sql. Such as how the API is doing.
2428 # Note that we use a whitespace test rather than a \b test to avoid
2429 # any remote case where a word like on may be inside of a table name
2430 # surrounded by symbols which may be considered word breaks.
2431 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
2432 $this->queryLogger
->warning(
2433 __METHOD__
. ": use of subqueries is not supported this way.",
2434 [ 'trace' => ( new RuntimeException() )->getTraceAsString() ]
2440 # Split database and table into proper variables.
2441 list( $database, $schema, $prefix, $table ) = $this->qualifiedTableComponents( $name );
2443 # Quote $table and apply the prefix if not quoted.
2444 # $tableName might be empty if this is called from Database::replaceVars()
2445 $tableName = "{$prefix}{$table}";
2446 if ( $format === 'quoted'
2447 && !$this->isQuotedIdentifier( $tableName )
2448 && $tableName !== ''
2450 $tableName = $this->addIdentifierQuotes( $tableName );
2453 # Quote $schema and $database and merge them with the table name if needed
2454 $tableName = $this->prependDatabaseOrSchema( $schema, $tableName, $format );
2455 $tableName = $this->prependDatabaseOrSchema( $database, $tableName, $format );
2461 * Get the table components needed for a query given the currently selected database
2463 * @param string $name Table name in the form of db.schema.table, db.table, or table
2464 * @return array (DB name or "" for default, schema name, table prefix, table name)
2466 protected function qualifiedTableComponents( $name ) {
2467 # We reverse the explode so that database.table and table both output the correct table.
2468 $dbDetails = explode( '.', $name, 3 );
2469 if ( count( $dbDetails ) == 3 ) {
2470 list( $database, $schema, $table ) = $dbDetails;
2471 # We don't want any prefix added in this case
2473 } elseif ( count( $dbDetails ) == 2 ) {
2474 list( $database, $table ) = $dbDetails;
2475 # We don't want any prefix added in this case
2477 # In dbs that support it, $database may actually be the schema
2478 # but that doesn't affect any of the functionality here
2481 list( $table ) = $dbDetails;
2482 if ( isset( $this->tableAliases
[$table] ) ) {
2483 $database = $this->tableAliases
[$table]['dbname'];
2484 $schema = is_string( $this->tableAliases
[$table]['schema'] )
2485 ?
$this->tableAliases
[$table]['schema']
2486 : $this->relationSchemaQualifier();
2487 $prefix = is_string( $this->tableAliases
[$table]['prefix'] )
2488 ?
$this->tableAliases
[$table]['prefix']
2489 : $this->tablePrefix();
2492 $schema = $this->relationSchemaQualifier(); # Default schema
2493 $prefix = $this->tablePrefix(); # Default prefix
2497 return [ $database, $schema, $prefix, $table ];
2501 * @param string|null $namespace Database or schema
2502 * @param string $relation Name of table, view, sequence, etc...
2503 * @param string $format One of (raw, quoted)
2504 * @return string Relation name with quoted and merged $namespace as needed
2506 private function prependDatabaseOrSchema( $namespace, $relation, $format ) {
2507 if ( strlen( $namespace ) ) {
2508 if ( $format === 'quoted' && !$this->isQuotedIdentifier( $namespace ) ) {
2509 $namespace = $this->addIdentifierQuotes( $namespace );
2511 $relation = $namespace . '.' . $relation;
2517 public function tableNames() {
2518 $inArray = func_get_args();
2521 foreach ( $inArray as $name ) {
2522 $retVal[$name] = $this->tableName( $name );
2528 public function tableNamesN() {
2529 $inArray = func_get_args();
2532 foreach ( $inArray as $name ) {
2533 $retVal[] = $this->tableName( $name );
2540 * Get an aliased table name
2542 * This returns strings like "tableName AS newTableName" for aliased tables
2543 * and "(SELECT * from tableA) newTablename" for subqueries (e.g. derived tables)
2545 * @see Database::tableName()
2546 * @param string|Subquery $table Table name or object with a 'sql' field
2547 * @param string|bool $alias Table alias (optional)
2548 * @return string SQL name for aliased table. Will not alias a table to its own name
2550 protected function tableNameWithAlias( $table, $alias = false ) {
2551 if ( is_string( $table ) ) {
2552 $quotedTable = $this->tableName( $table );
2553 } elseif ( $table instanceof Subquery
) {
2554 $quotedTable = (string)$table;
2556 throw new InvalidArgumentException( "Table must be a string or Subquery." );
2559 if ( $alias === false ||
$alias === $table ) {
2560 if ( $table instanceof Subquery
) {
2561 throw new InvalidArgumentException( "Subquery table missing alias." );
2564 return $quotedTable;
2566 return $quotedTable . ' ' . $this->addIdentifierQuotes( $alias );
2571 * Gets an array of aliased table names
2573 * @param array $tables [ [alias] => table ]
2574 * @return string[] See tableNameWithAlias()
2576 protected function tableNamesWithAlias( $tables ) {
2578 foreach ( $tables as $alias => $table ) {
2579 if ( is_numeric( $alias ) ) {
2582 $retval[] = $this->tableNameWithAlias( $table, $alias );
2589 * Get an aliased field name
2590 * e.g. fieldName AS newFieldName
2592 * @param string $name Field name
2593 * @param string|bool $alias Alias (optional)
2594 * @return string SQL name for aliased field. Will not alias a field to its own name
2596 protected function fieldNameWithAlias( $name, $alias = false ) {
2597 if ( !$alias ||
(string)$alias === (string)$name ) {
2600 return $name . ' AS ' . $this->addIdentifierQuotes( $alias ); // PostgreSQL needs AS
2605 * Gets an array of aliased field names
2607 * @param array $fields [ [alias] => field ]
2608 * @return string[] See fieldNameWithAlias()
2610 protected function fieldNamesWithAlias( $fields ) {
2612 foreach ( $fields as $alias => $field ) {
2613 if ( is_numeric( $alias ) ) {
2616 $retval[] = $this->fieldNameWithAlias( $field, $alias );
2623 * Get the aliased table name clause for a FROM clause
2624 * which might have a JOIN and/or USE INDEX or IGNORE INDEX clause
2626 * @param array $tables ( [alias] => table )
2627 * @param array $use_index Same as for select()
2628 * @param array $ignore_index Same as for select()
2629 * @param array $join_conds Same as for select()
2632 protected function tableNamesWithIndexClauseOrJOIN(
2633 $tables, $use_index = [], $ignore_index = [], $join_conds = []
2637 $use_index = (array)$use_index;
2638 $ignore_index = (array)$ignore_index;
2639 $join_conds = (array)$join_conds;
2641 foreach ( $tables as $alias => $table ) {
2642 if ( !is_string( $alias ) ) {
2643 // No alias? Set it equal to the table name
2647 if ( is_array( $table ) ) {
2648 // A parenthesized group
2649 if ( count( $table ) > 1 ) {
2650 $joinedTable = '(' .
2651 $this->tableNamesWithIndexClauseOrJOIN(
2652 $table, $use_index, $ignore_index, $join_conds ) . ')';
2655 $innerTable = reset( $table );
2656 $innerAlias = key( $table );
2657 $joinedTable = $this->tableNameWithAlias(
2659 is_string( $innerAlias ) ?
$innerAlias : $innerTable
2663 $joinedTable = $this->tableNameWithAlias( $table, $alias );
2666 // Is there a JOIN clause for this table?
2667 if ( isset( $join_conds[$alias] ) ) {
2668 list( $joinType, $conds ) = $join_conds[$alias];
2669 $tableClause = $joinType;
2670 $tableClause .= ' ' . $joinedTable;
2671 if ( isset( $use_index[$alias] ) ) { // has USE INDEX?
2672 $use = $this->useIndexClause( implode( ',', (array)$use_index[$alias] ) );
2674 $tableClause .= ' ' . $use;
2677 if ( isset( $ignore_index[$alias] ) ) { // has IGNORE INDEX?
2678 $ignore = $this->ignoreIndexClause(
2679 implode( ',', (array)$ignore_index[$alias] ) );
2680 if ( $ignore != '' ) {
2681 $tableClause .= ' ' . $ignore;
2684 $on = $this->makeList( (array)$conds, self
::LIST_AND
);
2686 $tableClause .= ' ON (' . $on . ')';
2689 $retJOIN[] = $tableClause;
2690 } elseif ( isset( $use_index[$alias] ) ) {
2691 // Is there an INDEX clause for this table?
2692 $tableClause = $joinedTable;
2693 $tableClause .= ' ' . $this->useIndexClause(
2694 implode( ',', (array)$use_index[$alias] )
2697 $ret[] = $tableClause;
2698 } elseif ( isset( $ignore_index[$alias] ) ) {
2699 // Is there an INDEX clause for this table?
2700 $tableClause = $joinedTable;
2701 $tableClause .= ' ' . $this->ignoreIndexClause(
2702 implode( ',', (array)$ignore_index[$alias] )
2705 $ret[] = $tableClause;
2707 $tableClause = $joinedTable;
2709 $ret[] = $tableClause;
2713 // We can't separate explicit JOIN clauses with ',', use ' ' for those
2714 $implicitJoins = $ret ?
implode( ',', $ret ) : "";
2715 $explicitJoins = $retJOIN ?
implode( ' ', $retJOIN ) : "";
2717 // Compile our final table clause
2718 return implode( ' ', [ $implicitJoins, $explicitJoins ] );
2722 * Allows for index remapping in queries where this is not consistent across DBMS
2724 * @param string $index
2727 protected function indexName( $index ) {
2728 return $this->indexAliases
[$index] ??
$index;
2731 public function addQuotes( $s ) {
2732 if ( $s instanceof Blob
) {
2735 if ( $s === null ) {
2737 } elseif ( is_bool( $s ) ) {
2740 # This will also quote numeric values. This should be harmless,
2741 # and protects against weird problems that occur when they really
2742 # _are_ strings such as article titles and string->number->string
2743 # conversion is not 1:1.
2744 return "'" . $this->strencode( $s ) . "'";
2748 public function addIdentifierQuotes( $s ) {
2749 return '"' . str_replace( '"', '""', $s ) . '"';
2753 * Returns if the given identifier looks quoted or not according to
2754 * the database convention for quoting identifiers .
2756 * @note Do not use this to determine if untrusted input is safe.
2757 * A malicious user can trick this function.
2758 * @param string $name
2761 public function isQuotedIdentifier( $name ) {
2762 return $name[0] == '"' && substr( $name, -1, 1 ) == '"';
2767 * @param string $escapeChar
2770 protected function escapeLikeInternal( $s, $escapeChar = '`' ) {
2771 return str_replace( [ $escapeChar, '%', '_' ],
2772 [ "{$escapeChar}{$escapeChar}", "{$escapeChar}%", "{$escapeChar}_" ],
2776 public function buildLike() {
2777 $params = func_get_args();
2779 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
2780 $params = $params[0];
2785 // We use ` instead of \ as the default LIKE escape character, since addQuotes()
2786 // may escape backslashes, creating problems of double escaping. The `
2787 // character has good cross-DBMS compatibility, avoiding special operators
2788 // in MS SQL like ^ and %
2791 foreach ( $params as $value ) {
2792 if ( $value instanceof LikeMatch
) {
2793 $s .= $value->toString();
2795 $s .= $this->escapeLikeInternal( $value, $escapeChar );
2800 $this->addQuotes( $s ) . ' ESCAPE ' . $this->addQuotes( $escapeChar ) . ' ';
2803 public function anyChar() {
2804 return new LikeMatch( '_' );
2807 public function anyString() {
2808 return new LikeMatch( '%' );
2811 public function nextSequenceValue( $seqName ) {
2816 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
2817 * is only needed because a) MySQL must be as efficient as possible due to
2818 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2819 * which index to pick. Anyway, other databases might have different
2820 * indexes on a given table. So don't bother overriding this unless you're
2822 * @param string $index
2825 public function useIndexClause( $index ) {
2830 * IGNORE INDEX clause. Unlikely to be useful for anything but MySQL. This
2831 * is only needed because a) MySQL must be as efficient as possible due to
2832 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2833 * which index to pick. Anyway, other databases might have different
2834 * indexes on a given table. So don't bother overriding this unless you're
2836 * @param string $index
2839 public function ignoreIndexClause( $index ) {
2843 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
2844 if ( count( $rows ) == 0 ) {
2848 $uniqueIndexes = (array)$uniqueIndexes;
2850 if ( !is_array( reset( $rows ) ) ) {
2855 $this->startAtomic( $fname, self
::ATOMIC_CANCELABLE
);
2856 $affectedRowCount = 0;
2857 foreach ( $rows as $row ) {
2858 // Delete rows which collide with this one
2859 $indexWhereClauses = [];
2860 foreach ( $uniqueIndexes as $index ) {
2861 $indexColumns = (array)$index;
2862 $indexRowValues = array_intersect_key( $row, array_flip( $indexColumns ) );
2863 if ( count( $indexRowValues ) != count( $indexColumns ) ) {
2864 throw new DBUnexpectedError(
2866 'New record does not provide all values for unique key (' .
2867 implode( ', ', $indexColumns ) . ')'
2869 } elseif ( in_array( null, $indexRowValues, true ) ) {
2870 throw new DBUnexpectedError(
2872 'New record has a null value for unique key (' .
2873 implode( ', ', $indexColumns ) . ')'
2876 $indexWhereClauses[] = $this->makeList( $indexRowValues, LIST_AND
);
2879 if ( $indexWhereClauses ) {
2880 $this->delete( $table, $this->makeList( $indexWhereClauses, LIST_OR
), $fname );
2881 $affectedRowCount +
= $this->affectedRows();
2884 // Now insert the row
2885 $this->insert( $table, $row, $fname );
2886 $affectedRowCount +
= $this->affectedRows();
2888 $this->endAtomic( $fname );
2889 $this->affectedRowCount
= $affectedRowCount;
2890 } catch ( Exception
$e ) {
2891 $this->cancelAtomic( $fname );
2897 * REPLACE query wrapper for MySQL and SQLite, which have a native REPLACE
2900 * @param string $table Table name
2901 * @param array|string $rows Row(s) to insert
2902 * @param string $fname Caller function name
2904 protected function nativeReplace( $table, $rows, $fname ) {
2905 $table = $this->tableName( $table );
2908 if ( !is_array( reset( $rows ) ) ) {
2912 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
2915 foreach ( $rows as $row ) {
2922 $sql .= '(' . $this->makeList( $row ) . ')';
2925 $this->query( $sql, $fname );
2928 public function upsert( $table, array $rows, $uniqueIndexes, array $set,
2931 if ( $rows === [] ) {
2932 return true; // nothing to do
2935 $uniqueIndexes = (array)$uniqueIndexes;
2936 if ( !is_array( reset( $rows ) ) ) {
2940 if ( count( $uniqueIndexes ) ) {
2941 $clauses = []; // list WHERE clauses that each identify a single row
2942 foreach ( $rows as $row ) {
2943 foreach ( $uniqueIndexes as $index ) {
2944 $index = is_array( $index ) ?
$index : [ $index ]; // columns
2945 $rowKey = []; // unique key to this row
2946 foreach ( $index as $column ) {
2947 $rowKey[$column] = $row[$column];
2949 $clauses[] = $this->makeList( $rowKey, self
::LIST_AND
);
2952 $where = [ $this->makeList( $clauses, self
::LIST_OR
) ];
2957 $affectedRowCount = 0;
2959 $this->startAtomic( $fname, self
::ATOMIC_CANCELABLE
);
2960 # Update any existing conflicting row(s)
2961 if ( $where !== false ) {
2962 $this->update( $table, $set, $where, $fname );
2963 $affectedRowCount +
= $this->affectedRows();
2965 # Now insert any non-conflicting row(s)
2966 $this->insert( $table, $rows, $fname, [ 'IGNORE' ] );
2967 $affectedRowCount +
= $this->affectedRows();
2968 $this->endAtomic( $fname );
2969 $this->affectedRowCount
= $affectedRowCount;
2970 } catch ( Exception
$e ) {
2971 $this->cancelAtomic( $fname );
2978 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
2982 throw new DBUnexpectedError( $this, __METHOD__
. ' called with empty $conds' );
2985 $delTable = $this->tableName( $delTable );
2986 $joinTable = $this->tableName( $joinTable );
2987 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
2988 if ( $conds != '*' ) {
2989 $sql .= 'WHERE ' . $this->makeList( $conds, self
::LIST_AND
);
2993 $this->query( $sql, $fname );
2996 public function textFieldSize( $table, $field ) {
2997 $table = $this->tableName( $table );
2998 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
2999 $res = $this->query( $sql, __METHOD__
);
3000 $row = $this->fetchObject( $res );
3004 if ( preg_match( '/\((.*)\)/', $row->Type
, $m ) ) {
3013 public function delete( $table, $conds, $fname = __METHOD__
) {
3015 throw new DBUnexpectedError( $this, __METHOD__
. ' called with no conditions' );
3018 $table = $this->tableName( $table );
3019 $sql = "DELETE FROM $table";
3021 if ( $conds != '*' ) {
3022 if ( is_array( $conds ) ) {
3023 $conds = $this->makeList( $conds, self
::LIST_AND
);
3025 $sql .= ' WHERE ' . $conds;
3028 $this->query( $sql, $fname );
3033 final public function insertSelect(
3034 $destTable, $srcTable, $varMap, $conds,
3035 $fname = __METHOD__
, $insertOptions = [], $selectOptions = [], $selectJoinConds = []
3037 static $hints = [ 'NO_AUTO_COLUMNS' ];
3039 $insertOptions = (array)$insertOptions;
3040 $selectOptions = (array)$selectOptions;
3042 if ( $this->cliMode
&& $this->isInsertSelectSafe( $insertOptions, $selectOptions ) ) {
3043 // For massive migrations with downtime, we don't want to select everything
3044 // into memory and OOM, so do all this native on the server side if possible.
3045 $this->nativeInsertSelect(
3051 array_diff( $insertOptions, $hints ),
3056 $this->nonNativeInsertSelect(
3062 array_diff( $insertOptions, $hints ),
3072 * @param array $insertOptions INSERT options
3073 * @param array $selectOptions SELECT options
3074 * @return bool Whether an INSERT SELECT with these options will be replication safe
3077 protected function isInsertSelectSafe( array $insertOptions, array $selectOptions ) {
3082 * Implementation of insertSelect() based on select() and insert()
3084 * @see IDatabase::insertSelect()
3086 * @param string $destTable
3087 * @param string|array $srcTable
3088 * @param array $varMap
3089 * @param array $conds
3090 * @param string $fname
3091 * @param array $insertOptions
3092 * @param array $selectOptions
3093 * @param array $selectJoinConds
3095 protected function nonNativeInsertSelect( $destTable, $srcTable, $varMap, $conds,
3096 $fname = __METHOD__
,
3097 $insertOptions = [], $selectOptions = [], $selectJoinConds = []
3099 // For web requests, do a locking SELECT and then INSERT. This puts the SELECT burden
3100 // on only the master (without needing row-based-replication). It also makes it easy to
3101 // know how big the INSERT is going to be.
3103 foreach ( $varMap as $dstColumn => $sourceColumnOrSql ) {
3104 $fields[] = $this->fieldNameWithAlias( $sourceColumnOrSql, $dstColumn );
3106 $selectOptions[] = 'FOR UPDATE';
3107 $res = $this->select(
3108 $srcTable, implode( ',', $fields ), $conds, $fname, $selectOptions, $selectJoinConds
3115 $affectedRowCount = 0;
3116 $this->startAtomic( $fname, self
::ATOMIC_CANCELABLE
);
3119 foreach ( $res as $row ) {
3120 $rows[] = (array)$row;
3122 // Avoid inserts that are too huge
3123 if ( count( $rows ) >= $this->nonNativeInsertSelectBatchSize
) {
3124 $ok = $this->insert( $destTable, $rows, $fname, $insertOptions );
3128 $affectedRowCount +
= $this->affectedRows();
3132 if ( $rows && $ok ) {
3133 $ok = $this->insert( $destTable, $rows, $fname, $insertOptions );
3135 $affectedRowCount +
= $this->affectedRows();
3139 $this->endAtomic( $fname );
3140 $this->affectedRowCount
= $affectedRowCount;
3142 $this->cancelAtomic( $fname );
3144 } catch ( Exception
$e ) {
3145 $this->cancelAtomic( $fname );
3151 * Native server-side implementation of insertSelect() for situations where
3152 * we don't want to select everything into memory
3154 * @see IDatabase::insertSelect()
3155 * @param string $destTable
3156 * @param string|array $srcTable
3157 * @param array $varMap
3158 * @param array $conds
3159 * @param string $fname
3160 * @param array $insertOptions
3161 * @param array $selectOptions
3162 * @param array $selectJoinConds
3164 protected function nativeInsertSelect( $destTable, $srcTable, $varMap, $conds,
3165 $fname = __METHOD__
,
3166 $insertOptions = [], $selectOptions = [], $selectJoinConds = []
3168 $destTable = $this->tableName( $destTable );
3170 if ( !is_array( $insertOptions ) ) {
3171 $insertOptions = [ $insertOptions ];
3174 $insertOptions = $this->makeInsertOptions( $insertOptions );
3176 $selectSql = $this->selectSQLText(
3178 array_values( $varMap ),
3185 $sql = "INSERT $insertOptions" .
3186 " INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ') ' .
3189 $this->query( $sql, $fname );
3193 * Construct a LIMIT query with optional offset. This is used for query
3194 * pages. The SQL should be adjusted so that only the first $limit rows
3195 * are returned. If $offset is provided as well, then the first $offset
3196 * rows should be discarded, and the next $limit rows should be returned.
3197 * If the result of the query is not ordered, then the rows to be returned
3198 * are theoretically arbitrary.
3200 * $sql is expected to be a SELECT, if that makes a difference.
3202 * The version provided by default works in MySQL and SQLite. It will very
3203 * likely need to be overridden for most other DBMSes.
3205 * @param string $sql SQL query we will append the limit too
3206 * @param int $limit The SQL limit
3207 * @param int|bool $offset The SQL offset (default false)
3208 * @throws DBUnexpectedError
3211 public function limitResult( $sql, $limit, $offset = false ) {
3212 if ( !is_numeric( $limit ) ) {
3213 throw new DBUnexpectedError( $this,
3214 "Invalid non-numeric limit passed to limitResult()\n" );
3217 return "$sql LIMIT "
3218 . ( ( is_numeric( $offset ) && $offset != 0 ) ?
"{$offset}," : "" )
3222 public function unionSupportsOrderAndLimit() {
3223 return true; // True for almost every DB supported
3226 public function unionQueries( $sqls, $all ) {
3227 $glue = $all ?
') UNION ALL (' : ') UNION (';
3229 return '(' . implode( $glue, $sqls ) . ')';
3232 public function unionConditionPermutations(
3233 $table, $vars, array $permute_conds, $extra_conds = '', $fname = __METHOD__
,
3234 $options = [], $join_conds = []
3236 // First, build the Cartesian product of $permute_conds
3238 foreach ( $permute_conds as $field => $values ) {
3240 // Skip empty $values
3243 $values = array_unique( $values ); // For sanity
3245 foreach ( $conds as $cond ) {
3246 foreach ( $values as $value ) {
3247 $cond[$field] = $value;
3248 $newConds[] = $cond; // Arrays are by-value, not by-reference, so this works
3254 $extra_conds = $extra_conds === '' ?
[] : (array)$extra_conds;
3256 // If there's just one condition and no subordering, hand off to
3257 // selectSQLText directly.
3258 if ( count( $conds ) === 1 &&
3259 ( !isset( $options['INNER ORDER BY'] ) ||
!$this->unionSupportsOrderAndLimit() )
3261 return $this->selectSQLText(
3262 $table, $vars, $conds[0] +
$extra_conds, $fname, $options, $join_conds
3266 // Otherwise, we need to pull out the order and limit to apply after
3267 // the union. Then build the SQL queries for each set of conditions in
3268 // $conds. Then union them together (using UNION ALL, because the
3269 // product *should* already be distinct).
3270 $orderBy = $this->makeOrderBy( $options );
3271 $limit = $options['LIMIT'] ??
null;
3272 $offset = $options['OFFSET'] ??
false;
3273 $all = empty( $options['NOTALL'] ) && !in_array( 'NOTALL', $options );
3274 if ( !$this->unionSupportsOrderAndLimit() ) {
3275 unset( $options['ORDER BY'], $options['LIMIT'], $options['OFFSET'] );
3277 if ( array_key_exists( 'INNER ORDER BY', $options ) ) {
3278 $options['ORDER BY'] = $options['INNER ORDER BY'];
3280 if ( $limit !== null && is_numeric( $offset ) && $offset != 0 ) {
3281 // We need to increase the limit by the offset rather than
3282 // using the offset directly, otherwise it'll skip incorrectly
3283 // in the subqueries.
3284 $options['LIMIT'] = $limit +
$offset;
3285 unset( $options['OFFSET'] );
3290 foreach ( $conds as $cond ) {
3291 $sqls[] = $this->selectSQLText(
3292 $table, $vars, $cond +
$extra_conds, $fname, $options, $join_conds
3295 $sql = $this->unionQueries( $sqls, $all ) . $orderBy;
3296 if ( $limit !== null ) {
3297 $sql = $this->limitResult( $sql, $limit, $offset );
3303 public function conditional( $cond, $trueVal, $falseVal ) {
3304 if ( is_array( $cond ) ) {
3305 $cond = $this->makeList( $cond, self
::LIST_AND
);
3308 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
3311 public function strreplace( $orig, $old, $new ) {
3312 return "REPLACE({$orig}, {$old}, {$new})";
3315 public function getServerUptime() {
3319 public function wasDeadlock() {
3323 public function wasLockTimeout() {
3327 public function wasConnectionLoss() {
3328 return $this->wasConnectionError( $this->lastErrno() );
3331 public function wasReadOnlyError() {
3335 public function wasErrorReissuable() {
3337 $this->wasDeadlock() ||
3338 $this->wasLockTimeout() ||
3339 $this->wasConnectionLoss()
3344 * Do not use this method outside of Database/DBError classes
3346 * @param int|string $errno
3347 * @return bool Whether the given query error was a connection drop
3349 public function wasConnectionError( $errno ) {
3354 * @return bool Whether it is known that the last query error only caused statement rollback
3355 * @note This is for backwards compatibility for callers catching DBError exceptions in
3356 * order to ignore problems like duplicate key errors or foriegn key violations
3359 protected function wasKnownStatementRollbackError() {
3360 return false; // don't know; it could have caused a transaction rollback
3363 public function deadlockLoop() {
3364 $args = func_get_args();
3365 $function = array_shift( $args );
3366 $tries = self
::DEADLOCK_TRIES
;
3368 $this->begin( __METHOD__
);
3371 /** @var Exception $e */
3375 $retVal = $function( ...$args );
3377 } catch ( DBQueryError
$e ) {
3378 if ( $this->wasDeadlock() ) {
3379 // Retry after a randomized delay
3380 usleep( mt_rand( self
::DEADLOCK_DELAY_MIN
, self
::DEADLOCK_DELAY_MAX
) );
3382 // Throw the error back up
3386 } while ( --$tries > 0 );
3388 if ( $tries <= 0 ) {
3389 // Too many deadlocks; give up
3390 $this->rollback( __METHOD__
);
3393 $this->commit( __METHOD__
);
3399 public function masterPosWait( DBMasterPos
$pos, $timeout ) {
3400 # Real waits are implemented in the subclass.
3404 public function getReplicaPos() {
3409 public function getMasterPos() {
3414 public function serverIsReadOnly() {
3418 final public function onTransactionResolution( callable
$callback, $fname = __METHOD__
) {
3419 if ( !$this->trxLevel
) {
3420 throw new DBUnexpectedError( $this, "No transaction is active." );
3422 $this->trxEndCallbacks
[] = [ $callback, $fname, $this->currentAtomicSectionId() ];
3425 final public function onTransactionCommitOrIdle( callable
$callback, $fname = __METHOD__
) {
3426 if ( !$this->trxLevel
&& $this->getTransactionRoundId() ) {
3427 // Start an implicit transaction similar to how query() does
3428 $this->begin( __METHOD__
, self
::TRANSACTION_INTERNAL
);
3429 $this->trxAutomatic
= true;
3432 $this->trxIdleCallbacks
[] = [ $callback, $fname, $this->currentAtomicSectionId() ];
3433 if ( !$this->trxLevel
) {
3434 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_IDLE
);
3438 final public function onTransactionIdle( callable
$callback, $fname = __METHOD__
) {
3439 $this->onTransactionCommitOrIdle( $callback, $fname );
3442 final public function onTransactionPreCommitOrIdle( callable
$callback, $fname = __METHOD__
) {
3443 if ( !$this->trxLevel
&& $this->getTransactionRoundId() ) {
3444 // Start an implicit transaction similar to how query() does
3445 $this->begin( __METHOD__
, self
::TRANSACTION_INTERNAL
);
3446 $this->trxAutomatic
= true;
3449 if ( $this->trxLevel
) {
3450 $this->trxPreCommitCallbacks
[] = [ $callback, $fname, $this->currentAtomicSectionId() ];
3452 // No transaction is active nor will start implicitly, so make one for this callback
3453 $this->startAtomic( __METHOD__
, self
::ATOMIC_CANCELABLE
);
3456 $this->endAtomic( __METHOD__
);
3457 } catch ( Exception
$e ) {
3458 $this->cancelAtomic( __METHOD__
);
3465 * @return AtomicSectionIdentifier|null ID of the topmost atomic section level
3467 private function currentAtomicSectionId() {
3468 if ( $this->trxLevel
&& $this->trxAtomicLevels
) {
3469 $levelInfo = end( $this->trxAtomicLevels
);
3471 return $levelInfo[1];
3478 * @param AtomicSectionIdentifier $old
3479 * @param AtomicSectionIdentifier $new
3481 private function reassignCallbacksForSection(
3482 AtomicSectionIdentifier
$old, AtomicSectionIdentifier
$new
3484 foreach ( $this->trxPreCommitCallbacks
as $key => $info ) {
3485 if ( $info[2] === $old ) {
3486 $this->trxPreCommitCallbacks
[$key][2] = $new;
3489 foreach ( $this->trxIdleCallbacks
as $key => $info ) {
3490 if ( $info[2] === $old ) {
3491 $this->trxIdleCallbacks
[$key][2] = $new;
3494 foreach ( $this->trxEndCallbacks
as $key => $info ) {
3495 if ( $info[2] === $old ) {
3496 $this->trxEndCallbacks
[$key][2] = $new;
3502 * @param AtomicSectionIdentifier[] $sectionIds ID of an actual savepoint
3503 * @throws UnexpectedValueException
3505 private function modifyCallbacksForCancel( array $sectionIds ) {
3506 // Cancel the "on commit" callbacks owned by this savepoint
3507 $this->trxIdleCallbacks
= array_filter(
3508 $this->trxIdleCallbacks
,
3509 function ( $entry ) use ( $sectionIds ) {
3510 return !in_array( $entry[2], $sectionIds, true );
3513 $this->trxPreCommitCallbacks
= array_filter(
3514 $this->trxPreCommitCallbacks
,
3515 function ( $entry ) use ( $sectionIds ) {
3516 return !in_array( $entry[2], $sectionIds, true );
3519 // Make "on resolution" callbacks owned by this savepoint to perceive a rollback
3520 foreach ( $this->trxEndCallbacks
as $key => $entry ) {
3521 if ( in_array( $entry[2], $sectionIds, true ) ) {
3522 $callback = $entry[0];
3523 $this->trxEndCallbacks
[$key][0] = function () use ( $callback ) {
3524 return $callback( self
::TRIGGER_ROLLBACK
, $this );
3530 final public function setTransactionListener( $name, callable
$callback = null ) {
3532 $this->trxRecurringCallbacks
[$name] = $callback;
3534 unset( $this->trxRecurringCallbacks
[$name] );
3539 * Whether to disable running of post-COMMIT/ROLLBACK callbacks
3541 * This method should not be used outside of Database/LoadBalancer
3543 * @param bool $suppress
3546 final public function setTrxEndCallbackSuppression( $suppress ) {
3547 $this->trxEndCallbacksSuppressed
= $suppress;
3551 * Actually consume and run any "on transaction idle/resolution" callbacks.
3553 * This method should not be used outside of Database/LoadBalancer
3555 * @param int $trigger IDatabase::TRIGGER_* constant
3556 * @return int Number of callbacks attempted
3560 public function runOnTransactionIdleCallbacks( $trigger ) {
3561 if ( $this->trxLevel
) { // sanity
3562 throw new DBUnexpectedError( $this, __METHOD__
. ': a transaction is still open.' );
3565 if ( $this->trxEndCallbacksSuppressed
) {
3570 $autoTrx = $this->getFlag( self
::DBO_TRX
); // automatic begin() enabled?
3571 /** @var Exception $e */
3572 $e = null; // first exception
3573 do { // callbacks may add callbacks :)
3574 $callbacks = array_merge(
3575 $this->trxIdleCallbacks
,
3576 $this->trxEndCallbacks
// include "transaction resolution" callbacks
3578 $this->trxIdleCallbacks
= []; // consumed (and recursion guard)
3579 $this->trxEndCallbacks
= []; // consumed (recursion guard)
3580 foreach ( $callbacks as $callback ) {
3582 list( $phpCallback ) = $callback;
3583 $this->clearFlag( self
::DBO_TRX
); // make each query its own transaction
3585 call_user_func( $phpCallback, $trigger, $this );
3586 } catch ( Exception
$ex ) {
3587 call_user_func( $this->errorLogger
, $ex );
3589 // Some callbacks may use startAtomic/endAtomic, so make sure
3590 // their transactions are ended so other callbacks don't fail
3591 if ( $this->trxLevel() ) {
3592 $this->rollback( __METHOD__
, self
::FLUSHING_INTERNAL
);
3596 $this->setFlag( self
::DBO_TRX
); // restore automatic begin()
3598 $this->clearFlag( self
::DBO_TRX
); // restore auto-commit
3602 } while ( count( $this->trxIdleCallbacks
) );
3604 if ( $e instanceof Exception
) {
3605 throw $e; // re-throw any first exception
3612 * Actually consume and run any "on transaction pre-commit" callbacks.
3614 * This method should not be used outside of Database/LoadBalancer
3617 * @return int Number of callbacks attempted
3620 public function runOnTransactionPreCommitCallbacks() {
3623 $e = null; // first exception
3624 do { // callbacks may add callbacks :)
3625 $callbacks = $this->trxPreCommitCallbacks
;
3626 $this->trxPreCommitCallbacks
= []; // consumed (and recursion guard)
3627 foreach ( $callbacks as $callback ) {
3630 list( $phpCallback ) = $callback;
3631 $phpCallback( $this );
3632 } catch ( Exception
$ex ) {
3633 ( $this->errorLogger
)( $ex );
3637 } while ( count( $this->trxPreCommitCallbacks
) );
3639 if ( $e instanceof Exception
) {
3640 throw $e; // re-throw any first exception
3647 * Actually run any "transaction listener" callbacks.
3649 * This method should not be used outside of Database/LoadBalancer
3651 * @param int $trigger IDatabase::TRIGGER_* constant
3655 public function runTransactionListenerCallbacks( $trigger ) {
3656 if ( $this->trxEndCallbacksSuppressed
) {
3660 /** @var Exception $e */
3661 $e = null; // first exception
3663 foreach ( $this->trxRecurringCallbacks
as $phpCallback ) {
3665 $phpCallback( $trigger, $this );
3666 } catch ( Exception
$ex ) {
3667 ( $this->errorLogger
)( $ex );
3672 if ( $e instanceof Exception
) {
3673 throw $e; // re-throw any first exception
3678 * Create a savepoint
3680 * This is used internally to implement atomic sections. It should not be
3684 * @param string $identifier Identifier for the savepoint
3685 * @param string $fname Calling function name
3687 protected function doSavepoint( $identifier, $fname ) {
3688 $this->query( 'SAVEPOINT ' . $this->addIdentifierQuotes( $identifier ), $fname );
3692 * Release a savepoint
3694 * This is used internally to implement atomic sections. It should not be
3698 * @param string $identifier Identifier for the savepoint
3699 * @param string $fname Calling function name
3701 protected function doReleaseSavepoint( $identifier, $fname ) {
3702 $this->query( 'RELEASE SAVEPOINT ' . $this->addIdentifierQuotes( $identifier ), $fname );
3706 * Rollback to a savepoint
3708 * This is used internally to implement atomic sections. It should not be
3712 * @param string $identifier Identifier for the savepoint
3713 * @param string $fname Calling function name
3715 protected function doRollbackToSavepoint( $identifier, $fname ) {
3716 $this->query( 'ROLLBACK TO SAVEPOINT ' . $this->addIdentifierQuotes( $identifier ), $fname );
3720 * @param string $fname
3723 private function nextSavepointId( $fname ) {
3724 $savepointId = self
::$SAVEPOINT_PREFIX . ++
$this->trxAtomicCounter
;
3725 if ( strlen( $savepointId ) > 30 ) {
3726 // 30 == Oracle's identifier length limit (pre 12c)
3727 // With a 22 character prefix, that puts the highest number at 99999999.
3728 throw new DBUnexpectedError(
3730 'There have been an excessively large number of atomic sections in a transaction'
3731 . " started by $this->trxFname (at $fname)"
3735 return $savepointId;
3738 final public function startAtomic(
3739 $fname = __METHOD__
, $cancelable = self
::ATOMIC_NOT_CANCELABLE
3741 $savepointId = $cancelable === self
::ATOMIC_CANCELABLE ? self
::$NOT_APPLICABLE : null;
3743 if ( !$this->trxLevel
) {
3744 $this->begin( $fname, self
::TRANSACTION_INTERNAL
); // sets trxAutomatic
3745 // If DBO_TRX is set, a series of startAtomic/endAtomic pairs will result
3746 // in all changes being in one transaction to keep requests transactional.
3747 if ( $this->getFlag( self
::DBO_TRX
) ) {
3748 // Since writes could happen in between the topmost atomic sections as part
3749 // of the transaction, those sections will need savepoints.
3750 $savepointId = $this->nextSavepointId( $fname );
3751 $this->doSavepoint( $savepointId, $fname );
3753 $this->trxAutomaticAtomic
= true;
3755 } elseif ( $cancelable === self
::ATOMIC_CANCELABLE
) {
3756 $savepointId = $this->nextSavepointId( $fname );
3757 $this->doSavepoint( $savepointId, $fname );
3760 $sectionId = new AtomicSectionIdentifier
;
3761 $this->trxAtomicLevels
[] = [ $fname, $sectionId, $savepointId ];
3762 $this->queryLogger
->debug( 'startAtomic: entering level ' .
3763 ( count( $this->trxAtomicLevels
) - 1 ) . " ($fname)" );
3768 final public function endAtomic( $fname = __METHOD__
) {
3769 if ( !$this->trxLevel ||
!$this->trxAtomicLevels
) {
3770 throw new DBUnexpectedError( $this, "No atomic section is open (got $fname)." );
3773 // Check if the current section matches $fname
3774 $pos = count( $this->trxAtomicLevels
) - 1;
3775 list( $savedFname, $sectionId, $savepointId ) = $this->trxAtomicLevels
[$pos];
3776 $this->queryLogger
->debug( "endAtomic: leaving level $pos ($fname)" );
3778 if ( $savedFname !== $fname ) {
3779 throw new DBUnexpectedError(
3781 "Invalid atomic section ended (got $fname but expected $savedFname)."
3785 // Remove the last section (no need to re-index the array)
3786 array_pop( $this->trxAtomicLevels
);
3788 if ( !$this->trxAtomicLevels
&& $this->trxAutomaticAtomic
) {
3789 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
3790 } elseif ( $savepointId !== null && $savepointId !== self
::$NOT_APPLICABLE ) {
3791 $this->doReleaseSavepoint( $savepointId, $fname );
3794 // Hoist callback ownership for callbacks in the section that just ended;
3795 // all callbacks should have an owner that is present in trxAtomicLevels.
3796 $currentSectionId = $this->currentAtomicSectionId();
3797 if ( $currentSectionId ) {
3798 $this->reassignCallbacksForSection( $sectionId, $currentSectionId );
3802 final public function cancelAtomic(
3803 $fname = __METHOD__
, AtomicSectionIdentifier
$sectionId = null
3805 if ( !$this->trxLevel ||
!$this->trxAtomicLevels
) {
3806 throw new DBUnexpectedError( $this, "No atomic section is open (got $fname)." );
3809 $excisedFnames = [];
3810 if ( $sectionId !== null ) {
3811 // Find the (last) section with the given $sectionId
3813 foreach ( $this->trxAtomicLevels
as $i => list( $asFname, $asId, $spId ) ) {
3814 if ( $asId === $sectionId ) {
3819 throw new DBUnexpectedError( $this, "Atomic section not found (for $fname)" );
3821 // Remove all descendant sections and re-index the array
3823 $len = count( $this->trxAtomicLevels
);
3824 for ( $i = $pos +
1; $i < $len; ++
$i ) {
3825 $excisedFnames[] = $this->trxAtomicLevels
[$i][0];
3826 $excisedIds[] = $this->trxAtomicLevels
[$i][1];
3828 $this->trxAtomicLevels
= array_slice( $this->trxAtomicLevels
, 0, $pos +
1 );
3829 $this->modifyCallbacksForCancel( $excisedIds );
3832 // Check if the current section matches $fname
3833 $pos = count( $this->trxAtomicLevels
) - 1;
3834 list( $savedFname, $savedSectionId, $savepointId ) = $this->trxAtomicLevels
[$pos];
3836 if ( $excisedFnames ) {
3837 $this->queryLogger
->debug( "cancelAtomic: canceling level $pos ($savedFname) " .
3838 "and descendants " . implode( ', ', $excisedFnames ) );
3840 $this->queryLogger
->debug( "cancelAtomic: canceling level $pos ($savedFname)" );
3843 if ( $savedFname !== $fname ) {
3844 throw new DBUnexpectedError(
3846 "Invalid atomic section ended (got $fname but expected $savedFname)."
3850 // Remove the last section (no need to re-index the array)
3851 array_pop( $this->trxAtomicLevels
);
3852 $this->modifyCallbacksForCancel( [ $savedSectionId ] );
3854 if ( $savepointId !== null ) {
3855 // Rollback the transaction to the state just before this atomic section
3856 if ( $savepointId === self
::$NOT_APPLICABLE ) {
3857 $this->rollback( $fname, self
::FLUSHING_INTERNAL
);
3859 $this->doRollbackToSavepoint( $savepointId, $fname );
3860 $this->trxStatus
= self
::STATUS_TRX_OK
; // no exception; recovered
3861 $this->trxStatusIgnoredCause
= null;
3863 } elseif ( $this->trxStatus
> self
::STATUS_TRX_ERROR
) {
3864 // Put the transaction into an error state if it's not already in one
3865 $this->trxStatus
= self
::STATUS_TRX_ERROR
;
3866 $this->trxStatusCause
= new DBUnexpectedError(
3868 "Uncancelable atomic section canceled (got $fname)."
3872 $this->affectedRowCount
= 0; // for the sake of consistency
3875 final public function doAtomicSection(
3876 $fname, callable
$callback, $cancelable = self
::ATOMIC_NOT_CANCELABLE
3878 $sectionId = $this->startAtomic( $fname, $cancelable );
3880 $res = $callback( $this, $fname );
3881 } catch ( Exception
$e ) {
3882 $this->cancelAtomic( $fname, $sectionId );
3886 $this->endAtomic( $fname );
3891 final public function begin( $fname = __METHOD__
, $mode = self
::TRANSACTION_EXPLICIT
) {
3892 static $modes = [ self
::TRANSACTION_EXPLICIT
, self
::TRANSACTION_INTERNAL
];
3893 if ( !in_array( $mode, $modes, true ) ) {
3894 throw new DBUnexpectedError( $this, "$fname: invalid mode parameter '$mode'." );
3897 // Protect against mismatched atomic section, transaction nesting, and snapshot loss
3898 if ( $this->trxLevel
) {
3899 if ( $this->trxAtomicLevels
) {
3900 $levels = $this->flatAtomicSectionList();
3901 $msg = "$fname: Got explicit BEGIN while atomic section(s) $levels are open.";
3902 throw new DBUnexpectedError( $this, $msg );
3903 } elseif ( !$this->trxAutomatic
) {
3904 $msg = "$fname: Explicit transaction already active (from {$this->trxFname}).";
3905 throw new DBUnexpectedError( $this, $msg );
3907 $msg = "$fname: Implicit transaction already active (from {$this->trxFname}).";
3908 throw new DBUnexpectedError( $this, $msg );
3910 } elseif ( $this->getFlag( self
::DBO_TRX
) && $mode !== self
::TRANSACTION_INTERNAL
) {
3911 $msg = "$fname: Implicit transaction expected (DBO_TRX set).";
3912 throw new DBUnexpectedError( $this, $msg );
3915 $this->assertHasConnectionHandle();
3917 $this->doBegin( $fname );
3918 $this->trxStatus
= self
::STATUS_TRX_OK
;
3919 $this->trxStatusIgnoredCause
= null;
3920 $this->trxAtomicCounter
= 0;
3921 $this->trxTimestamp
= microtime( true );
3922 $this->trxFname
= $fname;
3923 $this->trxDoneWrites
= false;
3924 $this->trxAutomaticAtomic
= false;
3925 $this->trxAtomicLevels
= [];
3926 $this->trxShortId
= sprintf( '%06x', mt_rand( 0, 0xffffff ) );
3927 $this->trxWriteDuration
= 0.0;
3928 $this->trxWriteQueryCount
= 0;
3929 $this->trxWriteAffectedRows
= 0;
3930 $this->trxWriteAdjDuration
= 0.0;
3931 $this->trxWriteAdjQueryCount
= 0;
3932 $this->trxWriteCallers
= [];
3933 // First SELECT after BEGIN will establish the snapshot in REPEATABLE-READ.
3934 // Get an estimate of the replication lag before any such queries.
3935 $this->trxReplicaLag
= null; // clear cached value first
3936 $this->trxReplicaLag
= $this->getApproximateLagStatus()['lag'];
3937 // T147697: make explicitTrxActive() return true until begin() finishes. This way, no
3938 // caller will think its OK to muck around with the transaction just because startAtomic()
3939 // has not yet completed (e.g. setting trxAtomicLevels).
3940 $this->trxAutomatic
= ( $mode === self
::TRANSACTION_INTERNAL
);
3944 * Issues the BEGIN command to the database server.
3946 * @see Database::begin()
3947 * @param string $fname
3949 protected function doBegin( $fname ) {
3950 $this->query( 'BEGIN', $fname );
3951 $this->trxLevel
= 1;
3954 final public function commit( $fname = __METHOD__
, $flush = self
::FLUSHING_ONE
) {
3955 static $modes = [ self
::FLUSHING_ONE
, self
::FLUSHING_ALL_PEERS
, self
::FLUSHING_INTERNAL
];
3956 if ( !in_array( $flush, $modes, true ) ) {
3957 throw new DBUnexpectedError( $this, "$fname: invalid flush parameter '$flush'." );
3960 if ( $this->trxLevel
&& $this->trxAtomicLevels
) {
3961 // There are still atomic sections open; this cannot be ignored
3962 $levels = $this->flatAtomicSectionList();
3963 throw new DBUnexpectedError(
3965 "$fname: Got COMMIT while atomic sections $levels are still open."
3969 if ( $flush === self
::FLUSHING_INTERNAL ||
$flush === self
::FLUSHING_ALL_PEERS
) {
3970 if ( !$this->trxLevel
) {
3971 return; // nothing to do
3972 } elseif ( !$this->trxAutomatic
) {
3973 throw new DBUnexpectedError(
3975 "$fname: Flushing an explicit transaction, getting out of sync."
3979 if ( !$this->trxLevel
) {
3980 $this->queryLogger
->error(
3981 "$fname: No transaction to commit, something got out of sync." );
3982 return; // nothing to do
3983 } elseif ( $this->trxAutomatic
) {
3984 throw new DBUnexpectedError(
3986 "$fname: Expected mass commit of all peer transactions (DBO_TRX set)."
3991 $this->assertHasConnectionHandle();
3993 $this->runOnTransactionPreCommitCallbacks();
3995 $writeTime = $this->pendingWriteQueryDuration( self
::ESTIMATE_DB_APPLY
);
3996 $this->doCommit( $fname );
3997 $this->trxStatus
= self
::STATUS_TRX_NONE
;
3999 if ( $this->trxDoneWrites
) {
4000 $this->lastWriteTime
= microtime( true );
4001 $this->trxProfiler
->transactionWritingOut(
4003 $this->getDomainID(),
4006 $this->trxWriteAffectedRows
4010 // With FLUSHING_ALL_PEERS, callbacks will be explicitly run later
4011 if ( $flush !== self
::FLUSHING_ALL_PEERS
) {
4012 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_COMMIT
);
4013 $this->runTransactionListenerCallbacks( self
::TRIGGER_COMMIT
);
4018 * Issues the COMMIT command to the database server.
4020 * @see Database::commit()
4021 * @param string $fname
4023 protected function doCommit( $fname ) {
4024 if ( $this->trxLevel
) {
4025 $this->query( 'COMMIT', $fname );
4026 $this->trxLevel
= 0;
4030 final public function rollback( $fname = __METHOD__
, $flush = '' ) {
4031 $trxActive = $this->trxLevel
;
4033 if ( $flush !== self
::FLUSHING_INTERNAL
&& $flush !== self
::FLUSHING_ALL_PEERS
) {
4034 if ( $this->getFlag( self
::DBO_TRX
) ) {
4035 throw new DBUnexpectedError(
4037 "$fname: Expected mass rollback of all peer transactions (DBO_TRX set)."
4043 $this->assertHasConnectionHandle();
4045 $this->doRollback( $fname );
4046 $this->trxStatus
= self
::STATUS_TRX_NONE
;
4047 $this->trxAtomicLevels
= [];
4048 // Estimate the RTT via a query now that trxStatus is OK
4049 $writeTime = $this->pingAndCalculateLastTrxApplyTime();
4051 if ( $this->trxDoneWrites
) {
4052 $this->trxProfiler
->transactionWritingOut(
4054 $this->getDomainID(),
4057 $this->trxWriteAffectedRows
4062 // Clear any commit-dependant callbacks. They might even be present
4063 // only due to transaction rounds, with no SQL transaction being active
4064 $this->trxIdleCallbacks
= [];
4065 $this->trxPreCommitCallbacks
= [];
4067 // With FLUSHING_ALL_PEERS, callbacks will be explicitly run later
4068 if ( $trxActive && $flush !== self
::FLUSHING_ALL_PEERS
) {
4070 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_ROLLBACK
);
4071 } catch ( Exception
$e ) {
4072 // already logged; finish and let LoadBalancer move on during mass-rollback
4075 $this->runTransactionListenerCallbacks( self
::TRIGGER_ROLLBACK
);
4076 } catch ( Exception
$e ) {
4077 // already logged; let LoadBalancer move on during mass-rollback
4080 $this->affectedRowCount
= 0; // for the sake of consistency
4085 * Issues the ROLLBACK command to the database server.
4087 * @see Database::rollback()
4088 * @param string $fname
4090 protected function doRollback( $fname ) {
4091 if ( $this->trxLevel
) {
4092 # Disconnects cause rollback anyway, so ignore those errors
4093 $ignoreErrors = true;
4094 $this->query( 'ROLLBACK', $fname, $ignoreErrors );
4095 $this->trxLevel
= 0;
4099 public function flushSnapshot( $fname = __METHOD__
) {
4100 if ( $this->writesOrCallbacksPending() ||
$this->explicitTrxActive() ) {
4101 // This only flushes transactions to clear snapshots, not to write data
4102 $fnames = implode( ', ', $this->pendingWriteAndCallbackCallers() );
4103 throw new DBUnexpectedError(
4105 "$fname: Cannot flush snapshot because writes are pending ($fnames)."
4109 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
4112 public function explicitTrxActive() {
4113 return $this->trxLevel
&& ( $this->trxAtomicLevels ||
!$this->trxAutomatic
);
4116 public function duplicateTableStructure(
4117 $oldName, $newName, $temporary = false, $fname = __METHOD__
4119 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
4122 public function listTables( $prefix = null, $fname = __METHOD__
) {
4123 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
4126 public function listViews( $prefix = null, $fname = __METHOD__
) {
4127 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
4130 public function timestamp( $ts = 0 ) {
4131 $t = new ConvertibleTimestamp( $ts );
4132 // Let errors bubble up to avoid putting garbage in the DB
4133 return $t->getTimestamp( TS_MW
);
4136 public function timestampOrNull( $ts = null ) {
4137 if ( is_null( $ts ) ) {
4140 return $this->timestamp( $ts );
4144 public function affectedRows() {
4145 return ( $this->affectedRowCount
=== null )
4146 ?
$this->fetchAffectedRowCount() // default to driver value
4147 : $this->affectedRowCount
;
4151 * @return int Number of retrieved rows according to the driver
4153 abstract protected function fetchAffectedRowCount();
4156 * Take the result from a query, and wrap it in a ResultWrapper if
4157 * necessary. Boolean values are passed through as is, to indicate success
4158 * of write queries or failure.
4160 * Once upon a time, Database::query() returned a bare MySQL result
4161 * resource, and it was necessary to call this function to convert it to
4162 * a wrapper. Nowadays, raw database objects are never exposed to external
4163 * callers, so this is unnecessary in external code.
4165 * @param bool|ResultWrapper|resource $result
4166 * @return bool|ResultWrapper
4168 protected function resultObject( $result ) {
4171 } elseif ( $result instanceof ResultWrapper
) {
4173 } elseif ( $result === true ) {
4174 // Successful write query
4177 return new ResultWrapper( $this, $result );
4181 public function ping( &$rtt = null ) {
4182 // Avoid hitting the server if it was hit recently
4183 if ( $this->isOpen() && ( microtime( true ) - $this->lastPing
) < self
::PING_TTL
) {
4184 if ( !func_num_args() ||
$this->rttEstimate
> 0 ) {
4185 $rtt = $this->rttEstimate
;
4186 return true; // don't care about $rtt
4190 // This will reconnect if possible or return false if not
4191 $this->clearFlag( self
::DBO_TRX
, self
::REMEMBER_PRIOR
);
4192 $ok = ( $this->query( self
::PING_QUERY
, __METHOD__
, true ) !== false );
4193 $this->restoreFlags( self
::RESTORE_PRIOR
);
4196 $rtt = $this->rttEstimate
;
4203 * Close any existing (dead) database connection and open a new connection
4205 * @param string $fname
4206 * @return bool True if new connection is opened successfully, false if error
4208 protected function replaceLostConnection( $fname ) {
4209 $this->closeConnection();
4210 $this->opened
= false;
4211 $this->conn
= false;
4213 $this->handleSessionLossPreconnect();
4222 $this->tablePrefix()
4224 $this->lastPing
= microtime( true );
4227 $this->connLogger
->warning(
4228 $fname . ': lost connection to {dbserver}; reconnected',
4230 'dbserver' => $this->getServer(),
4231 'trace' => ( new RuntimeException() )->getTraceAsString()
4234 } catch ( DBConnectionError
$e ) {
4237 $this->connLogger
->error(
4238 $fname . ': lost connection to {dbserver} permanently',
4239 [ 'dbserver' => $this->getServer() ]
4243 $this->handleSessionLossPostconnect();
4248 public function getSessionLagStatus() {
4249 return $this->getRecordedTransactionLagStatus() ?
: $this->getApproximateLagStatus();
4253 * Get the replica DB lag when the current transaction started
4255 * This is useful when transactions might use snapshot isolation
4256 * (e.g. REPEATABLE-READ in innodb), so the "real" lag of that data
4257 * is this lag plus transaction duration. If they don't, it is still
4258 * safe to be pessimistic. This returns null if there is no transaction.
4260 * This returns null if the lag status for this transaction was not yet recorded.
4262 * @return array|null ('lag': seconds or false on error, 'since': UNIX timestamp of BEGIN)
4265 final protected function getRecordedTransactionLagStatus() {
4266 return ( $this->trxLevel
&& $this->trxReplicaLag
!== null )
4267 ?
[ 'lag' => $this->trxReplicaLag
, 'since' => $this->trxTimestamp() ]
4272 * Get a replica DB lag estimate for this server
4274 * @return array ('lag': seconds or false on error, 'since': UNIX timestamp of estimate)
4277 protected function getApproximateLagStatus() {
4279 'lag' => $this->getLBInfo( 'replica' ) ?
$this->getLag() : 0,
4280 'since' => microtime( true )
4285 * Merge the result of getSessionLagStatus() for several DBs
4286 * using the most pessimistic values to estimate the lag of
4287 * any data derived from them in combination
4289 * This is information is useful for caching modules
4291 * @see WANObjectCache::set()
4292 * @see WANObjectCache::getWithSetCallback()
4294 * @param IDatabase $db1
4295 * @param IDatabase|null $db2 [optional]
4296 * @return array Map of values:
4297 * - lag: highest lag of any of the DBs or false on error (e.g. replication stopped)
4298 * - since: oldest UNIX timestamp of any of the DB lag estimates
4299 * - pending: whether any of the DBs have uncommitted changes
4303 public static function getCacheSetOptions( IDatabase
$db1, IDatabase
$db2 = null ) {
4304 $res = [ 'lag' => 0, 'since' => INF
, 'pending' => false ];
4305 foreach ( func_get_args() as $db ) {
4306 /** @var IDatabase $db */
4307 $status = $db->getSessionLagStatus();
4308 if ( $status['lag'] === false ) {
4309 $res['lag'] = false;
4310 } elseif ( $res['lag'] !== false ) {
4311 $res['lag'] = max( $res['lag'], $status['lag'] );
4313 $res['since'] = min( $res['since'], $status['since'] );
4314 $res['pending'] = $res['pending'] ?
: $db->writesPending();
4320 public function getLag() {
4324 public function maxListLen() {
4328 public function encodeBlob( $b ) {
4332 public function decodeBlob( $b ) {
4333 if ( $b instanceof Blob
) {
4339 public function setSessionOptions( array $options ) {
4342 public function sourceFile(
4344 callable
$lineCallback = null,
4345 callable
$resultCallback = null,
4347 callable
$inputCallback = null
4349 Wikimedia\
suppressWarnings();
4350 $fp = fopen( $filename, 'r' );
4351 Wikimedia\restoreWarnings
();
4353 if ( $fp === false ) {
4354 throw new RuntimeException( "Could not open \"{$filename}\".\n" );
4358 $fname = __METHOD__
. "( $filename )";
4362 $error = $this->sourceStream(
4363 $fp, $lineCallback, $resultCallback, $fname, $inputCallback );
4364 } catch ( Exception
$e ) {
4374 public function setSchemaVars( $vars ) {
4375 $this->schemaVars
= $vars;
4378 public function sourceStream(
4380 callable
$lineCallback = null,
4381 callable
$resultCallback = null,
4382 $fname = __METHOD__
,
4383 callable
$inputCallback = null
4385 $delimiterReset = new ScopedCallback(
4386 function ( $delimiter ) {
4387 $this->delimiter
= $delimiter;
4389 [ $this->delimiter
]
4393 while ( !feof( $fp ) ) {
4394 if ( $lineCallback ) {
4395 call_user_func( $lineCallback );
4398 $line = trim( fgets( $fp ) );
4400 if ( $line == '' ) {
4404 if ( $line[0] == '-' && $line[1] == '-' ) {
4412 $done = $this->streamStatementEnd( $cmd, $line );
4416 if ( $done ||
feof( $fp ) ) {
4417 $cmd = $this->replaceVars( $cmd );
4419 if ( $inputCallback ) {
4420 $callbackResult = $inputCallback( $cmd );
4422 if ( is_string( $callbackResult ) ||
!$callbackResult ) {
4423 $cmd = $callbackResult;
4428 $res = $this->query( $cmd, $fname );
4430 if ( $resultCallback ) {
4431 $resultCallback( $res, $this );
4434 if ( $res === false ) {
4435 $err = $this->lastError();
4437 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
4444 ScopedCallback
::consume( $delimiterReset );
4449 * Called by sourceStream() to check if we've reached a statement end
4451 * @param string &$sql SQL assembled so far
4452 * @param string &$newLine New line about to be added to $sql
4453 * @return bool Whether $newLine contains end of the statement
4455 public function streamStatementEnd( &$sql, &$newLine ) {
4456 if ( $this->delimiter
) {
4458 $newLine = preg_replace(
4459 '/' . preg_quote( $this->delimiter
, '/' ) . '$/', '', $newLine );
4460 if ( $newLine != $prev ) {
4469 * Database independent variable replacement. Replaces a set of variables
4470 * in an SQL statement with their contents as given by $this->getSchemaVars().
4472 * Supports '{$var}' `{$var}` and / *$var* / (without the spaces) style variables.
4474 * - '{$var}' should be used for text and is passed through the database's
4476 * - `{$var}` should be used for identifiers (e.g. table and database names).
4477 * It is passed through the database's addIdentifierQuotes method which
4478 * can be overridden if the database uses something other than backticks.
4479 * - / *_* / or / *$wgDBprefix* / passes the name that follows through the
4480 * database's tableName method.
4481 * - / *i* / passes the name that follows through the database's indexName method.
4482 * - In all other cases, / *$var* / is left unencoded. Except for table options,
4483 * its use should be avoided. In 1.24 and older, string encoding was applied.
4485 * @param string $ins SQL statement to replace variables in
4486 * @return string The new SQL statement with variables replaced
4488 protected function replaceVars( $ins ) {
4489 $vars = $this->getSchemaVars();
4490 return preg_replace_callback(
4492 /\* (\$wgDBprefix|[_i]) \*/ (\w*) | # 1-2. tableName, indexName
4493 \'\{\$ (\w+) }\' | # 3. addQuotes
4494 `\{\$ (\w+) }` | # 4. addIdentifierQuotes
4495 /\*\$ (\w+) \*/ # 5. leave unencoded
4497 function ( $m ) use ( $vars ) {
4498 // Note: Because of <https://bugs.php.net/bug.php?id=51881>,
4499 // check for both nonexistent keys *and* the empty string.
4500 if ( isset( $m[1] ) && $m[1] !== '' ) {
4501 if ( $m[1] === 'i' ) {
4502 return $this->indexName( $m[2] );
4504 return $this->tableName( $m[2] );
4506 } elseif ( isset( $m[3] ) && $m[3] !== '' && array_key_exists( $m[3], $vars ) ) {
4507 return $this->addQuotes( $vars[$m[3]] );
4508 } elseif ( isset( $m[4] ) && $m[4] !== '' && array_key_exists( $m[4], $vars ) ) {
4509 return $this->addIdentifierQuotes( $vars[$m[4]] );
4510 } elseif ( isset( $m[5] ) && $m[5] !== '' && array_key_exists( $m[5], $vars ) ) {
4511 return $vars[$m[5]];
4521 * Get schema variables. If none have been set via setSchemaVars(), then
4522 * use some defaults from the current object.
4526 protected function getSchemaVars() {
4527 if ( $this->schemaVars
) {
4528 return $this->schemaVars
;
4530 return $this->getDefaultSchemaVars();
4535 * Get schema variables to use if none have been set via setSchemaVars().
4537 * Override this in derived classes to provide variables for tables.sql
4538 * and SQL patch files.
4542 protected function getDefaultSchemaVars() {
4546 public function lockIsFree( $lockName, $method ) {
4547 // RDBMs methods for checking named locks may or may not count this thread itself.
4548 // In MySQL, IS_FREE_LOCK() returns 0 if the thread already has the lock. This is
4549 // the behavior choosen by the interface for this method.
4550 return !isset( $this->namedLocksHeld
[$lockName] );
4553 public function lock( $lockName, $method, $timeout = 5 ) {
4554 $this->namedLocksHeld
[$lockName] = 1;
4559 public function unlock( $lockName, $method ) {
4560 unset( $this->namedLocksHeld
[$lockName] );
4565 public function getScopedLockAndFlush( $lockKey, $fname, $timeout ) {
4566 if ( $this->writesOrCallbacksPending() ) {
4567 // This only flushes transactions to clear snapshots, not to write data
4568 $fnames = implode( ', ', $this->pendingWriteAndCallbackCallers() );
4569 throw new DBUnexpectedError(
4571 "$fname: Cannot flush pre-lock snapshot because writes are pending ($fnames)."
4575 if ( !$this->lock( $lockKey, $fname, $timeout ) ) {
4579 $unlocker = new ScopedCallback( function () use ( $lockKey, $fname ) {
4580 if ( $this->trxLevel() ) {
4581 // There is a good chance an exception was thrown, causing any early return
4582 // from the caller. Let any error handler get a chance to issue rollback().
4583 // If there isn't one, let the error bubble up and trigger server-side rollback.
4584 $this->onTransactionResolution(
4585 function () use ( $lockKey, $fname ) {
4586 $this->unlock( $lockKey, $fname );
4591 $this->unlock( $lockKey, $fname );
4595 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
4600 public function namedLocksEnqueue() {
4604 public function tableLocksHaveTransactionScope() {
4608 final public function lockTables( array $read, array $write, $method ) {
4609 if ( $this->writesOrCallbacksPending() ) {
4610 throw new DBUnexpectedError( $this, "Transaction writes or callbacks still pending." );
4613 if ( $this->tableLocksHaveTransactionScope() ) {
4614 $this->startAtomic( $method );
4617 return $this->doLockTables( $read, $write, $method );
4621 * Helper function for lockTables() that handles the actual table locking
4623 * @param array $read Array of tables to lock for read access
4624 * @param array $write Array of tables to lock for write access
4625 * @param string $method Name of caller
4628 protected function doLockTables( array $read, array $write, $method ) {
4632 final public function unlockTables( $method ) {
4633 if ( $this->tableLocksHaveTransactionScope() ) {
4634 $this->endAtomic( $method );
4636 return true; // locks released on COMMIT/ROLLBACK
4639 return $this->doUnlockTables( $method );
4643 * Helper function for unlockTables() that handles the actual table unlocking
4645 * @param string $method Name of caller
4648 protected function doUnlockTables( $method ) {
4654 * @param string $tableName
4655 * @param string $fName
4656 * @return bool|ResultWrapper
4659 public function dropTable( $tableName, $fName = __METHOD__
) {
4660 if ( !$this->tableExists( $tableName, $fName ) ) {
4663 $sql = "DROP TABLE " . $this->tableName( $tableName ) . " CASCADE";
4665 return $this->query( $sql, $fName );
4668 public function getInfinity() {
4672 public function encodeExpiry( $expiry ) {
4673 return ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() )
4674 ?
$this->getInfinity()
4675 : $this->timestamp( $expiry );
4678 public function decodeExpiry( $expiry, $format = TS_MW
) {
4679 if ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() ) {
4683 return ConvertibleTimestamp
::convert( $format, $expiry );
4686 public function setBigSelects( $value = true ) {
4690 public function isReadOnly() {
4691 return ( $this->getReadOnlyReason() !== false );
4695 * @return string|bool Reason this DB is read-only or false if it is not
4697 protected function getReadOnlyReason() {
4698 $reason = $this->getLBInfo( 'readOnlyReason' );
4700 return is_string( $reason ) ?
$reason : false;
4703 public function setTableAliases( array $aliases ) {
4704 $this->tableAliases
= $aliases;
4707 public function setIndexAliases( array $aliases ) {
4708 $this->indexAliases
= $aliases;
4716 protected function hasFlags( $field, $flags ) {
4717 return ( ( $field & $flags ) === $flags );
4721 * Get the underlying binding connection handle
4723 * Makes sure the connection resource is set (disconnects and ping() failure can unset it).
4724 * This catches broken callers than catch and ignore disconnection exceptions.
4725 * Unlike checking isOpen(), this is safe to call inside of open().
4728 * @throws DBUnexpectedError
4731 protected function getBindingHandle() {
4732 if ( !$this->conn
) {
4733 throw new DBUnexpectedError(
4735 'DB connection was already closed or the connection dropped.'
4746 public function __toString() {
4747 return (string)$this->conn
;
4751 * Make sure that copies do not share the same client binding handle
4752 * @throws DBConnectionError
4754 public function __clone() {
4755 $this->connLogger
->warning(
4756 "Cloning " . static::class . " is not recommended; forking connection:\n" .
4757 ( new RuntimeException() )->getTraceAsString()
4760 if ( $this->isOpen() ) {
4761 // Open a new connection resource without messing with the old one
4762 $this->opened
= false;
4763 $this->conn
= false;
4764 $this->trxEndCallbacks
= []; // don't copy
4765 $this->handleSessionLossPreconnect(); // no trx or locks anymore
4772 $this->tablePrefix()
4774 $this->lastPing
= microtime( true );
4779 * Called by serialize. Throw an exception when DB connection is serialized.
4780 * This causes problems on some database engines because the connection is
4781 * not restored on unserialize.
4783 public function __sleep() {
4784 throw new RuntimeException( 'Database serialization may cause problems, since ' .
4785 'the connection is not restored on wakeup.' );
4789 * Run a few simple sanity checks and close dangling connections
4791 public function __destruct() {
4792 if ( $this->trxLevel
&& $this->trxDoneWrites
) {
4793 trigger_error( "Uncommitted DB writes (transaction from {$this->trxFname})." );
4796 $danglingWriters = $this->pendingWriteAndCallbackCallers();
4797 if ( $danglingWriters ) {
4798 $fnames = implode( ', ', $danglingWriters );
4799 trigger_error( "DB transaction writes or callbacks still pending ($fnames)." );
4802 if ( $this->conn
) {
4803 // Avoid connection leaks for sanity. Normally, resources close at script completion.
4804 // The connection might already be closed in zend/hhvm by now, so suppress warnings.
4805 Wikimedia\
suppressWarnings();
4806 $this->closeConnection();
4807 Wikimedia\restoreWarnings
();
4808 $this->conn
= false;
4809 $this->opened
= false;
4815 * @deprecated since 1.28
4817 class_alias( Database
::class, 'DatabaseBase' );
4820 * @deprecated since 1.29
4822 class_alias( Database
::class, 'Database' );